我正在使用C++(不是C++ 11)。我需要创建一个指向类内部函数的指针。我尝试执行以下操作:

void MyClass::buttonClickedEvent( int buttonId ) {
    // I need to have an access to all members of MyClass's class
}

void MyClass::setEvent() {

    void ( *func ) ( int );
    func = buttonClickedEvent; // <-- Reference to non static member function must be called

}

setEvent();

但是有一个错误:“必须调用对非静态成员函数的引用”。我该怎么做才能指向MyClass成员?

最佳答案

问题在于buttonClickedEvent是成员函数,您需要一个指向成员的指针才能调用它。

尝试这个:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

然后,当您调用它时,您需要一个MyClass类型的对象来执行此操作,例如this:
(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

关于c++ - 必须调用对非静态成员函数的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26331628/

10-12 16:41
查看更多