我一直在思考和搜索这个问题,但我无法解决这个问题。
我想要一个对象,当复制到另一个对象时,两个对象共享某些成员变量。因此,当我更改 object1 的成员变量的值时,它也会更改 object2 中的变量。例子:
class ABC {
public:
int a = 5;
//...
}
int main() {
ABC object1;
ABC object2 = object1;
object2.a = 7; // now, object1.a is equal to 7
object1.a = 10; // now, object2.a is equal to 10
}
我了解复制构造函数,但我不确定它是否适用于此处或存在
更好的方法。我一直在考虑使用指针或引用,但无法成功。
请注意,我不希望所有对象共享相同的变量。
你需要的是一个指针。指针指向该对象,然后复制第一个对象的所有对象都只复制该指针,以便它们都指向同一对象。为了让生活变得轻松,我们可以使用std::shared_ptr为我们管理分配和取消分配。就像是:
#include <memory>
class Foo
{
private:
std::shared_ptr<int> bar;
public:
Foo() : bar(std::make_shared<int>()) {}
int& getBar() { return *bar; }
};
int main()
{
Foo a;
a.getBar() = 7;
Foo b = a;
b.getBar() = 10;
// now getBar returns 10 for both a and b
Foo c;
// a and b are both 10 and c is 0 since it wasn't a copy and is it's own instance
b = c;
// now b and c are both 0 and a is still 10
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)