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

醉酒当歌 提交于 2019-12-13 06:09:47

问题


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?


回答1:


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




回答2:


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.




回答3:


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;
};


来源:https://stackoverflow.com/questions/23750558/c-incomplete-type-is-not-allowed-class-inner-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!