C++ 为什么我无法使用在声明它的类之外全局声明的枚举?

标签 c++ enums scope declaration

现在,我的项目有两个类和一个主类。由于这两个类相互继承,因此它们都使用前向声明。在第一个对象中,在 #include 语句的正下方,我在类定义之前初始化了两个枚举。我可以在该类中很好地使用这两个枚举。但是,如果我尝试在继承第一个类的另一个类中使用这些枚举,则会收到一条错误消息,指出枚举尚未声明。如果我尝试在第二类中重新定义枚举,则会收到重新定义错误。

我什至尝试使用我刚刚读到的技巧,并将每个枚举放在自己的命名空间中;这并没有改变任何事情。

这是一个例子:

#ifndef CLASSONE_H
#define CLASSONE_H

namespace Player
{
    enum Enum
    {
        One,
        Two,
    };
}

#endif

然后在第二个类中,我尝试使用之前声明的枚举:

void AddPlayer(Player::Enum playerNumber);

而是收到一条错误,指出“玩家”尚未声明。

最佳答案

在没有看到代码的情况下,我不确定您遇到了什么问题,但是可以编译:

enum OutsideEnum
{
    OE_1,
    OE_2,
};

namespace ns
{
    enum NSEnum
    {
       NE_1,
       NE_2,
    };
}

class Base
{
public:
    enum BaseEnum
    {
        BE_1,
        BE_2,
    };

    void BaseFunc();
};

class Derived
{
public:
    enum DerivedEnum
    {
        DE_1,
        DE_2,
    };

    void DerivedFunc();
};

void Base::BaseFunc()
{
    BaseEnum be = BE_1;
    Derived::DerivedEnum de = Derived::DE_1;
    OutsideEnum oe = OE_1;
    ns::NEEnum ne = ns::NE_1;
}

void Derived::DerivedFunc()
{
    Base::BaseEnum be = Base::BE_1;
    DerivedEnum de = DE_1;
    OutsideEnum oe = OE_1;
    ns::NEEnum ne = ns::NE_1;
}

int main()
{
    Base::BaseEnum be = Base::BE_1;
    Derived::DerivedEnum de = Derived::DE_1;
    OutsideEnum oe = OE_1;
    ns::NEEnum ne = ns::NE_1;
}

在类定义中定义枚举需要注意两件事:

  1. 如果您希望公开它,请确保将其声明为公开。
  2. 当从定义它的类以外的任何地方引用它时,请使用类名称来限定枚举的名称和值。

编辑:

好吧,问题与枚举无关,而与包含顺序有关,当您有基类和派生类时,只有派生类需要了解基类:

基类 header :

#ifndef BASE_H
#define BASE_H

enum BaseEnum
{
};

class Base
{
};
#endif

派生类头:

#ifndef DERIVED_H
#define DERIVED_H

#include "Base.h"

class Derived
{

   void Func(BaseEnum be);
};
#endif

关于C++ 为什么我无法使用在声明它的类之外全局声明的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2886800/

相关文章:

c++ - 使用一维迭代访问二维数组

java - JPA 实体 (Hibernate) 中的 ENUM 序号

java - 枚举的 toString 中的默认大小写

PHP - 包含文件而不继承变量?

PHP:分配新的 PDO 作为对象属性

c++ - SEH(结构化异常处理)机制在ARM上究竟是如何工作的?

c++ - 初级 C++ : Why is this switch statement giving me an error?

javascript - 我不断收到 "sum is not defined"错误

c++ - 具有使用可变参数模板的成员的类

android - 在 Room 中编写基于某个枚举值进行选择的类型安全查询