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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26331628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:35:10  来源:igfitidea点击:

Reference to non-static member function must be called

c++pointersreference

提问by JavaRunner

I'm using C++ (not C++11). I need to make a pointer to a function inside a class. I try to do following:

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

But there's an error: "Reference to non static member function must be called". What should I do to make a pointer to a member of MyClass?

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

回答by imreal

The problem is that buttonClickedEventis a member function and you need a pointer to member in order to invoke it.

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

Try this:

尝试这个:

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

And then when you invoke it, you need an object of type MyClassto do so, for example this:

然后当你调用它时,你需要一个类型的对象MyClass来这样做,例如this

(this->*func)(<argument>);

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

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

回答by xiaodong

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

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