如何通过指针调用函数

How to call a function by a pointer?

本文关键字:函数 调用 指针 何通过      更新时间:2023-10-16

我有一些基类,其中存储了一个指向派生类函数的指针。我需要从两个地方通过指针调用函数:来自 BaseClass 和来自派生类。

template < class T >
class BaseClass {
private:
    typedef void ( T::*FunctionPtr ) ();
    FunctionPtr funcPtr;
public:
    void setFunc( FunctionPtr funcPtr ) {
        this->funcPtr = funcPtr;
        ( this->*funcPtr )(); // I need to call it here also but it doesn't work
    }
};
class DerivedClass: public BaseClass < DerivedClass > {
public:
    void callMe() {
        printf( "Ok!n" );
    }
    void mainFunc() {
        setFunc( &DerivedClass::callMe );
        ( this->*funcPtr )(); // works fine here
    }   
};

错误:左操作数 to -> * 必须是指向与右操作数兼容的类的指针,但为"BaseClass *"

( this->*funcPtr )();

是用于调用funcPtr的错误语法,因为funcPtr的类型是 void T::*()

您需要使用:

( (static_cast<T*>(this))->*funcPtr )();