C++:从外部声明类内的枚举器,以便可以在私有成员中使用
class Printer;
enum Printer::States;
class Printer { // choose one of monitor or cormonitor
States taskStates[];
public:
enum States { Starting = 'S', Blocked = 'B', Unblocked = 'U', Finished = 'F', // general
Napping = 'N', Awake = 'A', // Santa
Working = 'W', NeedHelp = 'H', // elf
OnVacation = 'V', CheckingIn = 'I', // reindeer
DeliveringToys = 'D', DoneDelivering = 'd', // Santa, reindeer
Consulting = 'C', DoneConsulting = 'c' // Santa, elves
};
Printer();
void print( unsigned int id, States state );
void print( unsigned int id, States state, unsigned int numBlocked );
};
class Printer;
enum Printer::States;
class Printer { // choose one of monitor or cormonitor
States taskStates[];
public:
enum States { Starting = 'S', Blocked = 'B', Unblocked = 'U', Finished = 'F', // general
Napping = 'N', Awake = 'A', // Santa
Working = 'W', NeedHelp = 'H', // elf
OnVacation = 'V', CheckingIn = 'I', // reindeer
DeliveringToys = 'D', DoneDelivering = 'd', // Santa, reindeer
Consulting = 'C', DoneConsulting = 'c' // Santa, elves
};
Printer();
void print( unsigned int id, States state );
void print( unsigned int id, States state, unsigned int numBlocked );
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在类之外声明嵌套枚举。您还必须在使用它之前对其进行定义。
顺便说一句,C++11 的
enum class
只需在类内部声明 - 它可以在类外部定义。You can't declare nested enums outside of the class. You also have to have it be defined before you use it.
As a side-note, C++11's
enum class
only has to be declared inside the class - it can be defined outside of it.看起来您正在尝试前向声明一个枚举。在 C++03 中这是非法的。在 C++11 中,只要指定枚举的基础类型就可以做到这一点。来自维基百科: http://en.wikipedia.org/wiki/C%2B% 2B11#Strongly_typed_enumerations
因此,如果您的编译器支持前向声明枚举,您可以打开 C++0x/C++11 支持更改您的代码:
如果不是,您就无法将枚举范围限定为该类。您可以创建一个单独的命名空间并使用 typedef 来获得类似的语法:
然后在 Printer 类之外,在看到 Printer 类定义之前,您需要将 States 称为 Printer::States 而不是 Printer::州。了解 Printer 类定义后,您可以像往常一样将状态称为 Printer::States(因为 typedef)。
或者,如果您删除名称空间,您只需将它们称为状态。
It looks like you are trying to forward-declare an enumeration. In C++03 this is illegal. In C++11, you can do this as long as you specify the underlying type of the enum. From wikipedia: http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations
So if your compiler supports forward-declared enums, you can turn on C++0x/C++11 support change your code to:
If not, you can't scope your enum to the class. You could make a separate namespace and use a typedef to get similar syntax:
And then outside of the Printer class, before the Printer class definiton has been seen, you'll need to refer to States as printer::States rather than Printer::states. After the Printer class definition has been seen, you can refer to States as Printer::States as usual (because of the typedef).
Alternatively, if you drop the namespace you just refer to them as States.