Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何正确使用c++;班_C++_Copy Constructor_Assignment Operator - Fatal编程技术网

C++ 如何正确使用c++;班

C++ 如何正确使用c++;班,c++,copy-constructor,assignment-operator,C++,Copy Constructor,Assignment Operator,我已经为我的一个类的指针数据成员编写了复制构造函数 class person { public: string name; int number; }; class MyClass { int x; char c; std::string s; person student; MyClass::MyClass( const MyClass& other ) : x( other.x ), c( other.c ), s( o

我已经为我的一个类的指针数据成员编写了复制构造函数

class person
{
public:

 string name;
int number;
};



  class MyClass {
     int x;
    char c;
    std::string s;
    person student;
    MyClass::MyClass( const MyClass& other ) :
    x( other.x ), c( other.c ), s( other.s ),student(other.student){}
 };
但是当我运行这个程序时,我得到了以下错误

错误:成员“MyClass”[-fpPermissive]上的额外限定条件“MyClass::” 我是否正确使用了复制构造函数

MyClass::MyClass( const MyClass& other )
^^^^^^^^^^
只有在类定义之外定义主体时,才需要完全限定名。它告诉编译器这个特定函数(在您的例子中,它恰好是构造函数)属于名称限定类。
在类定义中定义主体时,意味着函数是在其中定义主体的类的成员,因此不需要完全限定名

class person
{
public:

string name;
int number;
};

 class MyClass {
 int x;
 char c;
 std::string s;
 person *student;
 MyClass(const MyClass& other);
};

MyClass::MyClass( const MyClass& other ) :
 x( other.x ), c( other.c ), s( other.s ),student(other.student){
  x = other.x;
  c = other.c;
  s = other.s;
  student = other.student;
 }
它现在编译得很好。我仍然有一个疑问,我是否正确地执行了显式复制构造函数和赋值操作。

如果您想要浅层复制,(所有
MyClass
实例都指向
student
的同一个副本),请执行以下操作:

MyClass::MyClass( const MyClass& other ) :
    x( other.x ), c( other.c ), s( other.s ), student( other.student ) {}
否则,您需要通过这种方式实现的深度复制(请注意取消引用):

运行以下代码以查看差异:

MyClass a;
person mike;
mike.name = "Mike Ross";
mike.number = 26;
a.student = &mike;
MyClass b(a);
b.student->number = 52;
cout << a.student->number << endl;
cout << b.student->number << endl;
深度复制输出:

52
52
26
52

正如错误消息所说,
MyClass::
是不必要的。(但这只是因为您在类的主体中内联定义构造函数。)您在显示的两个类中似乎都没有指针数据成员。您的复制ctor执行成员复制。编译器将生成的一个也会执行相同的操作。对于
student
,不会,因为它是一个指针,并且您正在将它分配给副本的
student
。除非这是您想要的行为(即所有MyClass实例都指向同一个
student
),否则您需要编写一个person构造函数来处理其成员的复制。此外,您不需要在构造函数体中重新分配成员。
26
52