【发布时间】: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