简体   繁体   中英

C++ incomplete type is not allowed class inner use?

I have a header Room.h defined as follows:

#ifndef ROOM_H
#define ROOM_H

class Room
{
public:
    Room();

private:
    Room north;
    Room south;
    Room east; 
    Room west;
};

#endif

But I get Error: incomplete type is not allowed for each of the Room variables. Is there a fundamental flaw in this kind of design?

Yes, the design is fatally flawed. You're saying each room contains four other rooms. Each of those would then contain four more rooms--and each of those four more rooms, and so on indefinitely. In short, what started as a single room contains infinite other rooms.

You can create a room that contains pointers to four other rooms. Then you can create rooms for those to connect to, but (importantly) when you get to the end of a chain, you can create a room that has null pointers in directions where there are no more rooms.

Short Answer

Use pointer.

private:
Room* north;
...

Long Answer

C++ compiler need know size of Class. Error: incomplete type is not allowed , because cannot compute size.

Use pointer. Because compiler can compute size of pointer .

PS : I'm not good at english

You are using Room type before completely defining it (from definition the compiler deduce the size which is required to create an object), and since it is same type inclusion, will lead to infinite definition. You can add pointer or reference to Room instead of object.

class Room
{
  public:
    Room();

  private:
   Room* north;
   Room* south;
   Room* east; 
   Room* west;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM