派生类如何从基类继承静态函数?
struct TimerEvent
{
event Event;
timeval TimeOut;
static void HandleTimer(int Fd, short Event, void *Arg);
};
HandleTimer 需要是静态的,因为我将它传递给 C 库 (libevent).
HandleTimer needs to be static since I'm passing it to C library (libevent).
我想继承这个类.这怎么办?
I want to inherit from this class. How can this be done?
谢谢.
推荐答案
您可以轻松继承该类:
class Derived: public TimerEvent {
...
};
但是,您不能在子类中覆盖 HandleTimer 并期望它起作用:
However, you can't override HandleTimer in your subclass and expect this to work:
TimerEvent *e = new Derived();
e->HandleTimer();
这是因为静态方法在 vtable 中没有条目,因此不能是虚拟的.但是,您可以使用void* Arg"将指针传递给您的实例……例如:
This is because static methods don't have an entry in the vtable, and can't thus be virtual. You can however use the "void* Arg" to pass a pointer to your instance... something like:
struct TimerEvent {
virtual void handle(int fd, short event) = 0;
static void HandleTimer(int fd, short event, void *arg) {
((TimerEvent *) arg)->handle(fd, event);
}
};
class Derived: public TimerEvent {
virtual void handle(int fd, short event) {
// whatever
}
};
这样,HandleTimer 仍然可以在 C 函数中使用,只需确保始终将真实"对象作为void* Arg"传递.
This way, HandleTimer can still be used from C functions, just make sure to always pass the "real" object as the "void* Arg".
相关文章