C++为什么我无法使用在声明的类之外全局声明的枚举?
现在,我的项目有两个类和一个主类。由于这两个类相互继承,因此它们都使用前向声明。在第一个对象中,在 #include 语句的正下方,我在类定义之前初始化了两个枚举。我可以在该类中很好地使用这两个枚举。但是,如果我尝试在继承第一个类的另一个类中使用这些枚举,则会收到一条错误消息,指出枚举尚未声明。如果我尝试在第二类中重新定义枚举,则会收到重新定义错误。
我什至尝试使用我刚刚读到的技巧,并将每个枚举放在自己的名称空间中;这并没有改变任何事情。
这是一个示例:
#ifndef CLASSONE_H
#define CLASSONE_H
namespace Player
{
enum Enum
{
One,
Two,
};
}
#endif
然后在第二个类中,我尝试使用之前声明的枚举:
void AddPlayer(Player::Enum playerNumber);
却收到一条错误消息,指出“玩家”尚未声明。
Right now, my project has two classes and a main. Since the two classes inherit from each other, they are both using forward declarations. In the first object, right underneath the #include statement, I initialize two enums, before the class definition. I can use both enums just fine inside that class. However, if I try to use those enums in the other class, which inherits from the first one, I get an error saying the enum has not been declared. If I try to redefine the enum in the second class, I get a redefinition error.
I have even tried using a trick I just read about, and putting each enum in its own namespace; that didn't change anything.
Here's an example:
#ifndef CLASSONE_H
#define CLASSONE_H
namespace Player
{
enum Enum
{
One,
Two,
};
}
#endif
Then inside the second class, I attempt to use the enum declared earlier:
void AddPlayer(Player::Enum playerNumber);
and instead get an error saying 'Player' has not been declared.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定您在没有看到代码的情况下遇到了什么问题,但是这可以编译:
在类定义中定义的枚举需要注意两件事:
编辑:
好的,问题与枚举无关,而是包含的顺序,当您有基类和派生类时,只有派生类需要了解基类:
基类标头:
派生类标头:
I'm not sure what issue you are having without seeing your code, but this compiles:
Two things to watch for with enums defined inside a class definition:
EDIT:
Ok, the problem has nothing to do with enums, but rather order of inclusion, when you have a base class and a derived class, only the derived class needs to know about the base class:
Base class header:
Derived class header: