类变量在其定义范围内?
这可能是一个愚蠢的问题。我正在尝试制作文本泥。我需要每个 Room 类包含其他 Room 类,以便在尝试移动到它们或从它们获取信息时可以引用。但是,我不能这样做,因为我显然无法在其定义中声明一个类。那么,我该怎么做呢?当我说我做不到时,我的意思是:
class Room {
public:
Room NorthRoom;
Room EastRoom;
Room SouthRoom;
Room WestRoom;
};
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;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不可能有
Room
成员变量。不过,您可以使用指针或引用。It's not possible to have a
Room
member variable. You could use a pointer or reference though.我确信不是每个房间都有四个儿童房,对吧?否则,你的房间数量是无限的,这在有限的内存中很难处理:-)
你可以尝试
然后,当房间没有孩子时,你可以拥有 NULL 指针。
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
Then you can have NULL pointers when a room doesn't have children.
您的
Room
需要有指向其他Room
(即Room*
)的指针。类类型对象(如
Room
)的大小至少足以容纳其所有成员变量(因此,如果将其每个成员变量的大小相加,您将得到类的最小大小。如果一个类可以包含其自己类型的成员变量,那么它的大小将是无限的(每个
Room
包含四个其他Room
,每个其中包含其他四个Room
,每个房间都包含...)。C++ 没有像 Java 和 C# 那样的引用类型对象。
Your
Room
needs to have pointers to otherRoom
s (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 otherRoom
s, each of which contains four otherRoom
s, each of which contains...).C++ doesn't have reference type objects like Java and C#.
您应该使用指针:
可能的原因是类还没有其构造函数,因此当您使用指针时,当类具有构造函数定义时,您会稍后初始化它们。
You should use pointers:
Probably cause is that class does not yet its constructor, so when you use pointers you init them later, when class has construcotr definition.