【问题标题】:how to properly use the copy constructor and assignment in c++ class如何在 C++ 类中正确使用复制构造函数和赋值
【发布时间】:2013-02-20 06:43:01
【问题描述】:

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

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”上的额外限定“MyClass::”[-fpermissive] 我是否正确使用了复制构造函数。

【问题讨论】:

  • 正如错误消息所说,MyClass:: 是不必要的。
  • (但只是因为您在类的主体中内联定义了构造函数。)
  • 在您展示的任何一个类中,您似乎都没有指针数据成员。您的复制 ctor 会按成员进行复制。编译器生成的那个也是一样的。

标签: c++ copy-constructor assignment-operator


【解决方案1】:
MyClass::MyClass( const MyClass& other )
^^^^^^^^^^

仅当您在类定义之外定义主体时,才需要完全限定名称。它告诉编译器这个特定的函数(在你的例子中恰好是构造函数)属于名称限定类。
当您在类定义中定义主体时,暗示该函数是您定义它的类的成员,因此不需要完全限定名称。

【讨论】:

    【解决方案2】:
    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;
     }
    

    现在可以正常编译了。我仍然有一个疑问,我是否正确地执行了显式复制构造函数和赋值操作。?

    【讨论】:

    • student 不适用,因为它是一个指针,您将其分配给副本的 student。除非这是您想要的行为(即所有 MyClass 实例都指向 student 的同一副本),否则您需要编写一个 person 构造函数来处理其成员的复制。
    • 另外,您不需要在构造函数主体中再次重新分配成员。
    【解决方案3】:

    如果你想要浅拷贝,(所有MyClass 实例都指向student 的同一个拷贝),这样做:

    MyClass::MyClass( const MyClass& other ) :
        x( other.x ), c( other.c ), s( other.s ), student( other.student ) {}
    

    否则,您需要深拷贝,它是通过这种方式实现的(注意取消引用):

    MyClass::MyClass( const MyClass& other ) :
        x( other.x ), c( other.c ), s( other.s ) {
        student = new person(*(other.student)); // de-reference is required
    }
    

    运行以下代码,看看区别:

    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
    

    【讨论】:

      猜你喜欢
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 2019-10-23
      • 2017-07-08
      • 2020-06-13
      相关资源
      最近更新 更多