在 C++ 中:是否可以在不同的文件中继续命名枚举?
例如:
基类头文件具有:
enum FOO
{
FOO_A,
FOO_B,
FOO_C,
FOO_USERSTART
};
然后派生类具有:
enum FOO
{
FOO_USERA=FOO_USERSTART
FOO_USERB,
FOO_USERC
};
只是为了清楚我的用法,它是为了拥有一个事件处理程序,其中基类有事件,然后派生类可以添加事件。 派生类事件处理程序将检查它的事件,如果该事件不适合它,那么它将将该事件传递给基类。
class Base
{
public:
virtual void HandleFoo(FOO event);
};
class Derived: public Base
{
public:
void HandleFoo(FOO event);
};
void Base::HandleFoo(FOO event)
{
switch(event)
{
case FOO_A:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
}
}
void Derived::HandleFoo(FOO event)
{
switch(event)
{
case FOO_USERA:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
default:
/* not my event, must be for someone else */
Base::HandleFoo(event);
break;
}
}
For example:
Base class header file has:
enum FOO
{
FOO_A,
FOO_B,
FOO_C,
FOO_USERSTART
};
Then the derived class has:
enum FOO
{
FOO_USERA=FOO_USERSTART
FOO_USERB,
FOO_USERC
};
Just to be clear on my usage it is for having an event handler where the base class has events and then derived classes can add events. The derived classes event handler would check for it's events and if the event was not for it, then it would pass the event down to the base class.
class Base
{
public:
virtual void HandleFoo(FOO event);
};
class Derived: public Base
{
public:
void HandleFoo(FOO event);
};
void Base::HandleFoo(FOO event)
{
switch(event)
{
case FOO_A:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
}
}
void Derived::HandleFoo(FOO event)
{
switch(event)
{
case FOO_USERA:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
default:
/* not my event, must be for someone else */
Base::HandleFoo(event);
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可以。一旦编译器看到 },就需要能够决定枚举是否适合 char、short、int 或 long。
因此,如果基类头有
编译器可能会决定枚举适合 16 位。 然后它可以使用它,例如在布局基类时。 如果您稍后能够将 1<<31 添加到枚举,则基类枚举成员将无法保存枚举值之一。
No. The compiler needs to be able to decide whether the enum fits in a char, short, int or long once it sees the }.
So if the base class header has
a compiler may decide the enum fits in 16 bits. It can then use that, e.g. when laying out the base class. If you were later able to add 1<<31 to the enum, the base class enum member would not be able to hold one of the enum values.
是的,只要枚举都是类的成员。 如果不是,那么它们将属于同一类型,编译器会非常不高兴。
Yes, as long as the enum's are both members of a class. If they weren't then they would be of the same type and the compiler would be very unhappy.
是的,这有效。 为了稍微简化您的代码,我建议使用这种更常见的“扩展”枚举方法:
您仍然需要注意“无序”枚举。 (例如:FOO_A=15、FOO_B=11 等)
Yes, this works. To simplify your code a bit, I would suggest this, more common method of "extending" enums:
You still need to watch out for "out of order" enums. (Example: FOO_A=15, FOO_B=11, etc.)