[英]How should I write a copy constructor to initialise another object?
Say, as a simplified example, I have a class object House which also has an object Kitchen.比如说,作为一个简化的例子,我有一个 class object 房子,还有一个 object 厨房。
Here is the header file:这是 header 文件:
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
};
Copying houseId
works fine within the copy assignment function.在复制分配 function 中复制
houseId
工作正常。 But I'm getting an error referring to House::House(House const& other) { *this = other; }
但我在提到
House::House(House const& other) { *this = other; }
时遇到错误。 House::House(House const& other) { *this = other; }
as the following: House::House(House const& other) { *this = other; }
如下:
error: constructor for 'House' must explicitly initialize the member 'newKitchen' which does not have a default constructor
which I'm not sure about as I thought my declaration of a default constructor covered this?我不确定,因为我认为我的默认构造函数声明涵盖了这一点?
Firstly, your "default constructor" in Kitchen
is not a default constructor, it is a user-defined constructor.首先,您在
Kitchen
中的“默认构造函数”不是默认构造函数,它是用户定义的构造函数。 It should initialize the members, and also I would re-enable copy and move behavior following the rule of five .它应该初始化成员,并且我会按照五规则重新启用复制和移动行为。
class Kitchen {
private:
int width;
int height;
int length;
public:
// Use member initialization list
Kitchen(int _width, int _height, int _length) : width(_width), height(_height), length(_length) {}
// Rule of 5
Kitchen(Kitchen const&) = default;
Kitchen& operator=(Kitchen const&) = default;
Kitchen(Kitchen&&) = default;
Kitchen& operator=(Kitchen&&) = default;
};
Then later your House
can use this user-defined constructor in a similar way然后稍后你的
House
可以以类似的方式使用这个用户定义的构造函数
House(Kitchen _newKitchen, int _houseId) : houseId(_houseId), newKitchen(_newKitchen) {}
Note that your Kitchen
could simply be a POD aggregate type to save the trouble请注意,您的
Kitchen
可能只是 POD 聚合类型以节省麻烦
class Kitchen
{
public:
int width;
int height;
int length;
}
This will follow the "rule of zero" and will be default constructable, aggregate initializable, copyable, and moveable.这将遵循“零规则”,并且将是默认可构造、可聚合初始化、可复制和可移动的。 The same would then follow for your
House
class as well.你的
House
class 也会如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.