[c++]:构造函数中启动列表的问题
我偶然发现了一个我以前从未想过的问题。 这里是: 每个对象(在初始化列表中列出)的“构造函数”将被触发。
class B
{
public:
B() { cout<<"B Con\n";}
B(const B &b) { cout<<"B Copy Con\n";}
};
class A
{
public:
A(B &b):_m(b) { cout<<"A Con\n";}
A(const A &a):_m(a._m) { cout<<"A Copy Con\n";}
private:
B _m;
}
main()
{
B b;
A a(b);
}
然后我得到如下输出:
B Con
B Copy Con
A Con
根据输出,我认为 'A a(b)' 触发了 B 的复制构造函数。 如果我猜对了,那就意味着 'A(B &b):_m(b)' 触发 B 的复制构造函数。 为什么不是构造函数而是复制构造函数?
I stumbled across a question that I never thought about before.
Here it is:
each object's (listed in the initialization list) "constructor" will be triggered.
class B
{
public:
B() { cout<<"B Con\n";}
B(const B &b) { cout<<"B Copy Con\n";}
};
class A
{
public:
A(B &b):_m(b) { cout<<"A Con\n";}
A(const A &a):_m(a._m) { cout<<"A Copy Con\n";}
private:
B _m;
}
main()
{
B b;
A a(b);
}
then I got the output as follows:
B Con
B Copy Con
A Con
According to the output, I think, 'A a(b)' triggered B's copy constructor.
If I got right, then that means 'A(B &b):_m(b)' triggers B's copy constructor.
Why not constructor but copy-constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
原因是当您调用时
,复制构造函数
是唯一可以匹配参数列表的构造函数。您向其传递一个参数,该参数的类型为
B 类
。复制构造函数并不是什么超级特殊的东西 - 它只是一个参数化构造函数,一旦参数列表匹配,就会通过初始化列表调用它。
The reason is when you call
then the copy constructor
is the only one that could match the parameter list. You pass it one parameter and that parameter is of type
class B
.Copy constructor is not something super special - it is just a parameterized constructor that will be invoked via the initialization list once the parameter list matches.
因为你告诉编译器用
b
初始化_m
,那怎么会不调用复制构造函数呢?Because you're telling the compiler to initialize
_m
withb
, how would that not call the copy constructor?答案就在
A(B &b):_m(b)
您正在使用复制构造函数实例化 B _m。相反,如果您执行
A(B &b):_m()
,它将使用默认构造函数。The answer lies in the
A(B &b):_m(b)
You are instantiating B _m with the copy constructor.If instead you did
A(B &b):_m()
it would use the default constructor.这里
_m(b)
导致调用B(const B&)
,它是 B 的复制构造函数。因此,它在初始化_m
时首先打印B Copy Con
,然后进入A的构造函数体,打印A Con
。这就解释了一切。Here
_m(b)
causes invocation ofB(const B&)
which is B's copy-constructor. That is why, it first printsB Copy Con
when initializing_m
, then it enters into A's constructor body, and printsA Con
. That explains it all.