[英]initialize member array with constructor
我有一个像这样的 class School
。 Space
是一个抽象的 class,不要介意。
class school:public space
{
private:
schoolyard y;
stairs s;
floor floors[3];
int capa;
public:
school(int x):floors[1](x),floors[2](x),floors[3](x){
cout<<"a school has been created"<<endl;}
void move(student x);
~school();
};
floor
是另一个我想初始化的 class 。 这部分floors[1](x),floors[2](x),floors[3](x)
可能是错误的。 也许有人知道我如何初始化 class 中的对象数组?
应该:
school(int x) : floors{x, x, x}
{
std::cout << "a school has been created" << std::endl;
}
首先,arrays 是从 0 开始的,所以有效索引是 0-2,而不是 1-3。
其次,您不能像您尝试的那样在构造函数的成员初始化列表中初始化单个数组成员。
如果floor
没有 默认构造函数,您可以将floors[]
数组更改为保存floor*
指针,然后在构造函数主体中使用new
构造每个floor
object,例如:
class school : public space
{
private:
...
floor* floors[3];
...
public:
school(int x){
for (int i = 0; i < 3; ++i){
floors[i] = new floor(x);
}
// other initialization as needed...
cout << "a school has been created" << endl;
}
~school(){
for (int i = 0; i < 3; ++i){
delete floors[i];
}
}
...
};
请注意,使用这种方法,您需要遵循3/5/0 规则,这意味着还需要在 C++11 及更高版本中实现复制构造函数和复制赋值运算符,以及可选的移动构造函数和移动赋值操作:
...
#include <algorithm>
class school : public space
{
private:
...
floor* floors[3];
...
public:
school(int x){
for (int i = 0; i < 3; ++i){
floors[i] = new floor(x);
}
// other initializations as needed...
cout << "a school has been created" << endl;
}
school(const school &src){
for (int i = 0; i < 3; ++i){
floors[i] = new floor(*(src.floors[i]));
}
// other copies as needed...
cout << "a school has been copied" << endl;
}
school(school &&src){
for (int i = 0; i < 3; ++i){
floors[i] = src.floors[i];
src.floors[i] = nullptr;
}
// other moves as needed...
cout << "a school has been moved" << endl;
}
~school(){
for (int i = 0; i < 3; ++i){
delete floors[i];
}
}
school& operator=(const school &rhs){
if (this != &rhs){
school temp(rhs);
std::swap_ranges(floors, floors+3, temp.floors);
}
return *this;
}
school& operator=(school &&rhs){
school temp(std::move(rhs));
std::swap_ranges(floors, floors+3, temp.floors);
return *this;
}
...
};
但是, std::vector
会让事情变得更容易,让编译器为您处理所有这些细节,例如:
...
#include <vector>
class school : public space
{
private:
...
std::vector<floor> floors;
...
public:
school(int x): floors(3, floor(x)) {
cout << "a school has been created" << endl;
}
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.