必须调用对非静态成员函数的引用

Reference to non-static member function must be called

本文关键字:函数 引用 静态成员 调用      更新时间:2023-10-16

我使用的是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

您可能想看看https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs memfnptr类型,尤其是[33.1]"指针到成员函数"的类型与"指针到函数"的不同吗

您只需要在函数调用后添加括号,并在需要时传递参数