C++不完整类型是不允许类内部使用的?

Tra*_*iew 0 c++ types nested class

我有一个标题Room.h定义如下:

#ifndef ROOM_H
#define ROOM_H

class Room
{
public:
    Room();

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

#endif
Run Code Online (Sandbox Code Playgroud)

但是我得到Error: incomplete type is not allowed了每个Room变量.这种设计有根本​​缺陷吗?

Jer*_*fin 6

是的,设计存在致命缺陷.你说每个房间都有四个房间.然后,每个房间将包含四个房间 - 以及另外四个房间中的每个房间,等等无限期.简而言之,从单个房间开始包含无限的其他房间.

您可以创建一个包含指向其他四个房间的指针的房间.然后你可以为那些连接的人创建空间,但是(重要的是)当你到达一个链的末尾时,你可以创建一个房间,在没有房间的方向上有空指针.


小智 5

简答

使用指针.

private:
Room* north;
...
Run Code Online (Sandbox Code Playgroud)

答案很长

C++编译器需要知道Class的大小.Error: incomplete type is not allowed,因为无法计算大小.

使用指针.因为编译器可以计算大小pointer.

PS:我不擅长英语