调用指向成员函数的指针 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23686456/
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 00:31:32  来源:igfitidea点击:

Calling pointer-to-member function C++

c++function-pointers

提问by wolfPack88

I have a pointer to a member function defined within a class, e.g.:

我有一个指向类中定义的成员函数的指针,例如:

class Example {
   void (Example::*foo)();

   void foo2();
};

In my main code, I then set foo as:

在我的主代码中,我将 foo 设置为:

Example *a;
a->foo = &Example::foo2;

However, when I try to call foo:

但是,当我尝试调用 foo 时:

a->foo();

I get the following compile time error: "error: expression preceding parentheses of apparent call must have (pointer-to-) function type". I'm assuming I'm getting the syntax wrong somewhere, can someone point it out to me?

我收到以下编译时错误:“错误:明显调用括号前的表达式必须具有(指向)函数类型”。我假设我在某个地方弄错了语法,有人可以向我指出吗?

回答by Bob Fincheimer

to call it you would do: (a->*(a->foo))()

调用它你会这样做: (a->*(a->foo))()

(a->*X)(...)- dereferences a member function pointer - the parens around a->*Xare important for precedence.

(a->*X)(...)- 取消引用成员函数指针 - 周围的括号a->*X对于优先级很重要。

X = a->foo- in your example.

X = a->foo- 在你的例子中。

See ideone herefor working example

有关工作示例,请参见此处的ideone