【发布时间】:2018-08-06 16:51:44
【问题描述】:
我需要实现一个类的拷贝构造函数。
我的要求是所有对象都需要共享相同的数据。 示例:如果我更改了一个对象的名称,则所有其他对象都将获得新的对象名称。
这是我的代码:
#include <iostream>
using namespace std;
class Contact
{
public:
string name;
//Constructor:
Contact(string n){
name = n;
};
/*
// Copy constructor:
*/
};
int main(int argc, const char * argv[]) {
Contact c1("albert");
Contact c2 = c1; //create a copy of c1
c1.name = "mark"; //modify c1 name
cout << c2.name << endl; //My problem: I want this output is "mark"
return 0;
}
可以用指针吗?
我尝试了这段代码,但我得到了错误: “错误:需要左值作为赋值的左操作数”
// Copy constructor:
Contact (const Contact &c){
&( this -> name ) = &c.name;
}
【问题讨论】:
-
您不需要复制构造函数,您只需将
name设为静态即可。但这是一个好的设计选择的可能性很小。 -
听起来是
std::shared_ptr的完美用例。 -
你为什么想要那个?
-
这是一道面试题。
标签: c++ copy-constructor