gpt4 book ai didi

c++ - 为什么不调用成员类的拷贝构造函数?

转载 作者:太空狗 更新时间:2023-10-29 23:22:13 29 4
gpt4 key购买 nike

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

最佳答案

因为你没有调用member的拷贝构造函数。如果覆盖 fred 的默认复制构造函数,则需要显式复制成员。

fred(const fred& other) : member_(other.member_) {
cout<<"Calling fred copy constr"<<'\n';
}

关于c++ - 为什么不调用成员类的拷贝构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2550828/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com