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".
这篇关于派生类如何从基类继承静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:派生类如何从基类继承静态函数?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01