【发布时间】:2021-03-12 13:52:18
【问题描述】:
比如说,作为一个简化的例子,我有一个类对象 House,它也有一个对象 Kitchen。
这是头文件:
class Kitchen {
private:
int width;
int height;
int length;
public:
Kitchen(int width, height, length); // default constructor
};
class House {
private:
int houseId;
Kitchen newKitchen;
public:
House(Kitchen newKitchen, int houseId); // default constructor
House& operator=(House const& other); // copy assignment
House(House const& other); // copy constructor
~House(); // destructor
};
在复制分配功能中复制houseId 工作正常。但我收到一个错误,指的是House::House(House const& other) { *this = other; },如下所示:
error: constructor for 'House' must explicitly initialize the member 'newKitchen' which does not have a default constructor
我不确定,因为我认为我的默认构造函数声明涵盖了这一点?
【问题讨论】:
-
如果您的类成员中的所有内容都可以简单地复制,那么最好的选择就是根本不编写复制构造函数。编译器默认生成一个。
-
... 和
Kitchen(int width, height, length);和House(Kitchen newKitchen, int houseId);不是默认构造函数。 -
旁注:让赋值运算符使用复制构造函数通常更容易,而不是相反。当你有成员或者基类需要初始化的时候,赋值就不行了。
标签: c++ oop destructor