调用指针到成员函数C ++ [英] Calling pointer-to-member function C++

查看:771
本文介绍了调用指针到成员函数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

void foo2();
};

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

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

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

  a-> foo(); 

我得到以下编译时错误:错误:明显调用的括号之前的表达式必须有到 - )函数类型。我假设我在某处得到语法错误,有人可以指出它对我吗?

解决方案

将执行:(a-> *(a-> foo))()



(a-> * X)(...) - 解引用成员函数指针 - a-> * X 对于优先级很重要。



X = a-> foo >

请参阅ideone 这里了解工作示例


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:

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

However, when I try to call 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?

解决方案

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

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

X = a->foo - in your example.

See ideone here for working example

这篇关于调用指针到成员函数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆