c++ - 如何正确初始化复制构造函数(以类为参考的构造函数)
问题描述
如何初始化具有类作为引用的构造函数的复制构造函数。我根本不知道在冒号后面放什么来初始化它。
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&
是 const 引用,这也可以工作!另外,如果你可以写成Wrapper
一个聚合,它会自动得到一个拷贝构造函数:
class Wrapper {
public:
Value& val;
// copy constructor automatically generated
};
推荐阅读
- c++ - 使用 BFS 的字梯 2
- sql-server - 时态表可以对插入进行历史记录吗?
- r - 将数据标签添加到 R 中的堆积条形图
- c# - 具有额外类型的 XML 反序列化会引发错误
- reactjs - 在 Konvajs React 中绘制直线和矩形的问题
- elasticsearch - ElasticSearch 合并操作会重置文档的 _version 号吗?
- image - Flutter NetworkImage 不加载 URL
- linux - 服务器重新启动后自动运行的 Bash 脚本
- javascript - 如何将 sort() 与两个过滤器结合使用?
- javascript - 上一个/下一个按钮位于引导模式中幻灯片内的图像下方