C++虚拟继承和类型转换/复制构造函数混淆
我有下面的代码:
class A
{
};
class B: public virtual A
{
public:
B()
{
cerr << "B()";
}
B(const A& a)
{
cerr << "B(const A&)";
}
};
class C: public B
{
};
int main(int argc, char **argv)
{
B *b = new B(C());
}
令我惊讶的是 B(const A& a) 没有被调用。这是为什么?
I have the code below:
class A
{
};
class B: public virtual A
{
public:
B()
{
cerr << "B()";
}
B(const A& a)
{
cerr << "B(const A&)";
}
};
class C: public B
{
};
int main(int argc, char **argv)
{
B *b = new B(C());
}
To my surprise B(const A& a) isn't called. Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
B
还有一个隐式声明的复制构造函数,声明为 调用此隐式声明的成员函数是因为它比用户声明的类型更匹配
C
类型的参数构造函数,B(const A&)
。B
also has an implicitly declared copy constructor that is declared asThis implicitly declared member function is called because it is a better match for the argument of type
C
than your user-declared constructor,B(const A&)
.这是我在您的代码上尝试
clang++ -cc1 -ast-dump
时得到的结果,正如您所看到的,您的类
B
有一个隐式声明的(编译器合成的)复制构造函数。inline B(B const &) throw():
这是类型C
参数更好的匹配 James McNellis 在 他的回答。这就是为什么您看不到对B(const A& a)
的调用,因为它实际上从未被调用。This is what I got when I tried
clang++ -cc1 -ast-dump
on your codeAs you can see your class
B
has an implicitly declared(compiler synthesized) copy ctor.inline B(B const &) throw():
which is a better match for typeC
argument as James McNellis said in his answer. That's why you do not see a call toB(const A& a)
because it never gets called actually.