首页 > 解决方案 > 如何正确初始化复制构造函数(以类为参考的构造函数)

问题描述

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

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;
};

标签: c++constructor

解决方案


假设您有两个类Value, 和Wrapper

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&是 const 引用,这也可以工作!另外,如果你可以写成Wrapper一个聚合,它会自动得到一个拷贝构造函数:

class Wrapper {
   public:
    Value& val;

    // copy constructor automatically generated
};

推荐阅读