如何正确初始化复制构造函数(以类为引用的构造函数)
How to properly initialize copy constructor (of constructor with class as reference)
如何初始化引用类的构造函数的复制构造函数。我根本不知道在冒号后面放什么才能初始化它。
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;
};
假设您有两个类,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&
是一个常量引用,这也将起作用!此外,如果可以将Wrapper
编写为聚合,它将自动获取复制构造函数:
class Wrapper {
public:
Value& val;
// copy constructor automatically generated
};
相关文章:
- 在类构造函数中传递对外部函数的引用
- 在 c++ 中将变量作为结构构造函数中的引用传递
- C++ 尝试在不存在的构造函数中引用已删除的函数(使用 rapidJson)
- 移动构造函数和右值引用
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 在引用初始化中使用已删除的复制构造函数进行复制初始化
- 为什么我需要在转换构造函数上引用 this->?
- 关于隐式声明的复制构造函数的引用在逻辑上不清楚
- C++:右值引用构造函数和复制省略
- CLion - 无法解决类中对构造函数的未定义引用
- 当有右值构造函数可用时,为什么从右值调用类引用构造函数重载?
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 调用默认构造函数时不引用它
- C++ 构造函数传递对基类对象的引用
- 使用默认构造函数引用成员变量初始化错误
- 构造函数引用参数导致seg错误
- 未定义的类构造函数引用,当它被正确定义时
- 如何从父类构造函数引用重写的静态方法
- 创建构造函数引用全局变量的类的全局实例时,C++ 程序崩溃