简体   繁体   English

如何通过指针调用函数?

[英]How to call a function by a pointer?

I have some base class in which I store a pointer to a function from derived class. 我有一些基类,我在其中存储指向派生类中的函数的指针。 I need to call a function by its pointer from two places: from BaseClass and from derived class. 我需要从两个位置通过其指针调用函数:从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
    }   
};

Error: left hand operand to -> * must be a pointer to class compatible with the right hand operand, but is 'BaseClass *' 错误:指向-> *的左操作数必须是指向与右操作数兼容的类的指针,但它是'BaseClass *'

( this->*funcPtr )();

is the wrong syntax to use to call funcPtr since the type of funcPtr is void T::*() . 是错误的语法使用调用funcPtr因为类型funcPtrvoid T::*()

You need to use: 您需要使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM