提问者:小点点

在最初未指定大小的情况下声明数组时出错:<error-type>Crew::FlightAttendants不允许不完整的类型


所以在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);
        };

我想声明(但不是首先初始化)FlightAttendants[]数组,而不事先指定它的长度(我只想在之后指定它的大小)。 就像Java,例如,我们可以做:

    //JAVA CODE    
        class Lamp {
            private int nLightBulbs;
            private boolean lightBulbs[];
        
            Lamp(int nLightBulbs) {
                this.nLightBulbs = nLightBulbs;
                this.lightBulbs = new boolean[nLightBulbs];
            }
        }

这就是问题所在。


共1个答案

匿名用户

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实例的指针