为什么不调用成员类的复制构造函数?
class member
{
public:
member()
{
cout<<"Calling member constr"<<'\n';
}
member(const member&)
{
cout<<"Calling member copy constr"<<'\n';
}
};
class fred
{
public:
fred()
{
cout<<"calling fred constr"<<'\n';
}
fred(const fred &)
{
cout<<"Calling fred copy constr"<<'\n';
}
protected:
member member_;
};
int main()
{
fred a;
fred b=a;
}
Output:
Calling member constr
calling fred constr
**Calling member constr**
Calling fred copy constr
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为你没有调用
member
的复制构造函数。如果您重写fred
的默认复制构造函数,则需要显式复制成员。Because you did not call
member
's copy constructor. You need to copy the members explicitly if you override the default copy constructor offred
.它没有被调用,因为您明确要求编译器不要调用它。当您为类
fred
定义自己的复制构造函数时,您实际上是告诉编译器您想要将事情交给您自己并自己进行复制。由于您没有在fred
的复制构造函数中复制member_
,因此它不会被复制。如果你去掉了
fred
的复制构造函数的显式定义,编译器会为你提供一个隐式的定义,它会调用member
的复制构造函数来进行复制member_
。如果您坚持自己定义
fred
的复制构造函数,则必须自己复制member_
,正如KennyTM建议的那样。It isn't called because you explicitly asked the compiler not to call it. When you defined your own copy constructor for class
fred
, you essentially told the compiler that you wanted to take matters into your hands and do the copying yourself. Since you do nothing to copy themember_
in thefred
's copy constructor, it isn't copied.If you get rid of the explicit definition of
fred
's copy constructor, the compiler will provide an implicit one for you, which will call themember
's copy constructor to copymember_
.If you insist on defining
fred
's copy constructor yourself, you have to copymember_
yourself, as KennyTM suggested.如果类 A 有一个类 B 成员,并且您显式实现了类 A 的复制构造函数,那么您必须显式复制那里的成员,在本例中调用 B 复制构造函数,否则 B 成员将被默认构造,而不是复制构造。
If class A has a class B member and you explicitly implement the copy ctor for class A, then you must explicitly copy the members there, in this case call the B copy ctor, otherwise the B member will be default constructed, not copy constructed.
在这种情况下,您必须显式调用它。因为,你已经重载了构造函数。
顺便说一句,当我看到“Fred”时,它让我想起了这个有用的资源,请进一步了解 C++ 构造函数:http://www.parashift.com/c++-faq-lite/ctors.html
You have to explicitly call it in this case. Because, you have overloaded constructors.
Btw, When I see "Fred", it reminds me this useful resource, please have look for further understanding of C++ constructors: http://www.parashift.com/c++-faq-lite/ctors.html