如何正确初始化复制构造函数(以类为引用的构造函数)

How to properly initialize copy constructor (of constructor with class as reference)

本文关键字:构造函数 引用 何正确 初始化 复制      更新时间:2023-10-16

如何初始化引用类的构造函数的复制构造函数。我根本不知道在冒号后面放什么才能初始化它。

class Me{
 public:   
    Me (const otherMe& t)
    :other_me(t)
    {}
    //copy constructor
    Me(const Me& me)
    : /*what do you put here in order to write 
    the line of code bellow. I tried t(t), and gives me the 
    warning 'Me::t is initialized with itself [-Winit-self]' */
    {cout << t.getSomthing() << endl;}
 private:
    const otherMe& other_me;
};

假设您有两个类,ValueWrapper

class Value { // stuff... }; 
class Wrapper; // This one contains the reference

我们可以像这样编写构造函数和复制构造函数:

class Wrapper {
    Value& val;
   public:
    Wrapper(Value& v) : val(v) {}
    Wrapper(Wrapper const& w) : val(w.val) {}
};

如果Value&是一个常量引用,这也将起作用!此外,如果可以将Wrapper编写为聚合,它将自动获取复制构造函数:

class Wrapper {
   public:
    Value& val;
    // copy constructor automatically generated
};