Ans*_* PP 1 c++ class copy-constructor member-variables
我一直在思考和搜索这个,但我无法解决这个问题.我想要一个对象,当复制到另一个对象时,两个对象共享某个成员变量.因此,当我更改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
}
Run Code Online (Sandbox Code Playgroud)
我知道复制构造函数,但我不确定它是否适用于此处或者有更好的方法.我一直在考虑使用指针或引用,但不能成功.请注意,我不希望所有对象共享同一个变量.
你需要的是一个指针.指针指向对象,然后复制第一个对象的所有对象只是复制指针,以便它们都指向同一个东西.为了简化生活,我们可以使用a 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
}
Run Code Online (Sandbox Code Playgroud)