我应该如何编写复制构造函数来初始化另一个对象?
How should I write a copy constructor to initialise another object?
举个简单的例子,我有一个 class 对象 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
中的“默认构造函数”不是默认构造函数,它是用户定义的构造函数。它应该初始化成员,而且我会在 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;
};
然后你的 House
可以以类似的方式使用这个用户定义的构造函数
House(Kitchen _newKitchen, int _houseId) : houseId(_houseId), newKitchen(_newKitchen) {}
请注意,您的 Kitchen
可以简单地使用 POD 聚合类型来省去麻烦
class Kitchen
{
public:
int width;
int height;
int length;
}
这将遵循“零规则”,默认可构造、聚合可初始化、可复制和可移动。您的 House
class 也会遵循同样的规则。
举个简单的例子,我有一个 class 对象 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
中的“默认构造函数”不是默认构造函数,它是用户定义的构造函数。它应该初始化成员,而且我会在 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;
};
然后你的 House
可以以类似的方式使用这个用户定义的构造函数
House(Kitchen _newKitchen, int _houseId) : houseId(_houseId), newKitchen(_newKitchen) {}
请注意,您的 Kitchen
可以简单地使用 POD 聚合类型来省去麻烦
class Kitchen
{
public:
int width;
int height;
int length;
}
这将遵循“零规则”,默认可构造、聚合可初始化、可复制和可移动。您的 House
class 也会遵循同样的规则。