Derived类如何从Base类继承一个静态函数? [英] How can Derived class inherit a static function from Base class?

查看:221
本文介绍了Derived类如何从Base类继承一个静态函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  struct TimerEvent 
{
event Event;
timeval TimeOut;
static void HandleTimer(int Fd,short Event,void * Arg);
};

HandleTimer需要是静态的,因为我将它传递给C库(libevent)。



我想继承这个类。



感谢。

解决方案

容易继承该类:

  class Derived:public TimerEvent {
...
};但是,你不能覆盖你的子类中的HandleTimer,并期望这个工作:



  TimerEvent * e = new Derived(); 
e-> HandleTimer();

这是因为静态方法在vtable中没有条目,虚拟。然而,你可以使用void * Arg来传递一个指向你的实例的指针...:

  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。


struct TimerEvent
{
   event Event;
   timeval TimeOut;
   static void HandleTimer(int Fd, short Event, void *Arg);
};

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?

Thanks.

解决方案

You can easily inherit from that class:

class Derived: public TimerEvent {
    ...
};

However, you can't override HandleTimer in your subclass and expect this to work:

TimerEvent *e = new Derived();
e->HandleTimer();

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
    }
};

This way, HandleTimer can still be used from C functions, just make sure to always pass the "real" object as the "void* Arg".

这篇关于Derived类如何从Base类继承一个静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆