How can Derived class inherit a static function from Base class?(派生类如何从基类继承静态函数?)
问题描述
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".
这篇关于派生类如何从基类继承静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:派生类如何从基类继承静态函数?
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01