声明数组时未最初指定大小时出错:机组人员: <error-type> :空乘人员 不允许类型不完整



所以在C++中给定这个类。。。

//C++ CODE    
class Crew {
Person flightAttendants[]; //Error: <error-type> Crew::flightAttendants Incomplete type is not allowed.
Person captain, firstOfficer;
public:
Crew(Person, Person, Person);
};

我想在第一次初始化时声明(但NOT(flightAttendants[]数组,而不预先指定其长度(我只想在之后指定其大小(。例如,就像Java一样,我们可以在其中执行:

//JAVA CODE    
class Lamp {
private int nLightBulbs;
private boolean lightBulbs[];

Lamp(int nLightBulbs) {
this.nLightBulbs = nLightBulbs;
this.lightBulbs = new boolean[nLightBulbs];
}
}

这就是问题所在。

Person flightAttendants[];

例如

Person * flightAttendants;

然后就像在Java中一样:

this.lightBulbs = new boolean[nLightBulbs];

在C++中执行

flightAttendants = new Person[...expected size...];

但使用std::vector更实用

std::vector<Person> flightAttendants;

由于许多原因,包括能够获得其大小/调整其大小,以及不必管理Person * flightAttendants中使用的指针(甚至还有其他安全管理方法(


注意,在Java中,您总是操纵指向实例的指针,在C++中,我们可以选择,并且前面的数组/向量不记住指向Person实例的指针而是Person的实例

相关内容

最新更新