派生类如何从基类继承静态函数?

2023-12-02C/C++开发问题
3

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

问题描述

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".

这篇关于派生类如何从基类继承静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6