Class variable within its definition?

前提是你 提交于 2019-12-06 09:05:17

问题


This is probably a dumb question. I am trying to make a text-mud. I need each Room class to contain other Room classes that one can refer to when trying to move to them or get information from them. However, I can not do that because I obviously can not declare a class within its definition. So, how do I do this? Here's what I mean when I state I can not do it:

class Room {
    public:
        Room NorthRoom;
        Room EastRoom;
        Room SouthRoom;
        Room WestRoom;
};

回答1:


It's not possible to have a Room member variable. You could use a pointer or reference though.

class Room {
    public:
        Room* NorthRoom;
        Room* EastRoom;
        Room* SouthRoom;
        Room* WestRoom;
};



回答2:


I am sure not EVERY room has four children rooms, right? Otherwise the number of your rooms is infinity which is hard to handle in finite memory :-)

You might try

class Room {
    public:
        Room* NorthRoom;
        Room* EastRoom;
        Room* SouthRoom;
        Room* WestRoom;
};

Then you can have NULL pointers when a room doesn't have children.




回答3:


Your Room needs to have pointers to other Rooms (that is, Room*s).

A class type object (like Room) has a size that is at least large enough to contain all its member variables (so, if you add up the sizes of each of its member variables, you'll get the smallest size that the class can be.

If a class could contain member variables of its own type then its size would be infinite (each Room contains four other Rooms, each of which contains four other Rooms, each of which contains...).

C++ doesn't have reference type objects like Java and C#.




回答4:


You should use pointers:

class Room {
    public:
        Room* NorthRoom;
        Room* EastRoom;
        Room* SouthRoom;
        Room* WestRoom;
};

Probably cause is that class does not yet its constructor, so when you use pointers you init them later, when class has construcotr definition.



来源:https://stackoverflow.com/questions/4004673/class-variable-within-its-definition

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