【问题标题】:Forward declare unscoped enum in class complains private前向声明类中的无范围枚举抱怨私有
【发布时间】:2017-08-30 05:17:06
【问题描述】:

为什么下面的 c++11/14 代码不起作用?在这里,我在课堂上声明一个枚举。目标不是在类中拥有大量的枚举值 - 100 个枚举值 - 这使得类不可读。出于政治原因,我不能为此使用单独的范围枚举。

class A {
public:
  // forward declare the enum
  enum B : int;
  void func (B b) {}
};

// The actual declaration
enum A::B  : int {
    Val1,
    Val2,
};

int main ()
{
    // B is unscoped. so I should be able to use it as below?
    int a = A::Val1;
}

编译错误

tmp.cpp: In function ‘int main()’:
tmp.cpp:13:5: error: ‘A::B Val1’ is private
     Val1,
     ^

tmp.cpp:19:16: error: within this context
     int a = A::Val1;
                ^

但以下代码有效:

int a = A::B::Val1;

【问题讨论】:

  • 只是一个想法:也许是因为编译器不知道Val1 没有在A 或派生类范围内的多个枚举中声明 - 并防止这种可能性通过强制它是私有的。

标签: c++11 enums forward-declaration


【解决方案1】:

该错误出现在 G++ 中,但没有出现在 Visual C++ 和 clang 中。形式上,枚举的 id 可以用作命名空间,也可以跳过,但最后两个默认情况下会跳过它,而最新的 g++ 强制执行它。这可以通过编译器选项进行更改。必须使用枚举类的 id:

class A {
public:
  // forward declare the enum
  enum class B : int;
  void func (B b) {}
};

// The actual declaration
enum class A::B  : int {
    Val1,
    Val2,
};

int main ()
{
    int a = static_cast<int>(A::B::Val1); // no implicit cast
}

【讨论】:

  • 我可能没有完全得到你的答案。 int a = A::B::Val1; 无需演员即可工作。只有int a = A::Val1; 不起作用。我希望它可以作为 unscoped enum 工作。 int a = A::Val1 如果我将枚举放在类本身中代替前向声明,则可以正常工作。所以我的疑问是为什么会有这种行为差异。
  • @MGH 枚举类的作用域是强制性的,对于琐碎的枚举,就像你使用的枚举一样,它取决于编译器的设置,为什么,我不确定。可能默认情况下被视为枚举类?但不,这需要演员表。如果我没记错的话,带有“permissive”标志的 g++ 将允许这样做。
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 2010-09-09
相关资源
最近更新 更多