在类中使用成员函数指针

neu*_*rte 8 c++ pointer-to-member

给出一个示例类:

class Fred
{
public:
Fred() 
{
    func = &Fred::fa;
}

void run()
{
     int foo, bar;
     *func(foo,bar);
}

double fa(int x, int y);
double fb(int x, int y);

private:
double (Fred::*func)(int x, int y);
};
Run Code Online (Sandbox Code Playgroud)

我在通过指针"*func(foo,bar)"调用成员函数的行中遇到编译器错误,说:"术语不会计算为带有2个参数的函数".我究竟做错了什么?

fbr*_*eto 19

您需要的语法如下:

((object).*(ptrToMember)) 
Run Code Online (Sandbox Code Playgroud)

所以你的电话会是:

((*this).*(func))(foo, bar);
Run Code Online (Sandbox Code Playgroud)

我相信另一种语法是:

(this->*func)(foo, bar);
Run Code Online (Sandbox Code Playgroud)


Tho*_*mas 6

您需要以下时髦的语法来通过指针调用成员函数:

(this->*func)(foo, bar);
Run Code Online (Sandbox Code Playgroud)


Vij*_*hew 6

您需要注意两件事。首先是函数指针类型的声明:

private:
  typedef double (Fred::*fptr)(int x, int y);
  fptr func;
Run Code Online (Sandbox Code Playgroud)

接下来是使用指针调用函数的语法:

(this->*func)(foo,bar)
Run Code Online (Sandbox Code Playgroud)

这是将编译和运行的修改后的示例代码:

#include <iostream>

class Fred
{
public:
  Fred() 
  {
    func = &Fred::fa;
  }

  void run()
  {
    int foo = 10, bar = 20;
    std::cout << (this->*func)(foo,bar) << '\n';
  }

  double fa(int x, int y)
  {
    return (double)(x + y);
  }
  double fb(int x, int y)
  {
  }

private:
  typedef double (Fred::*fptr)(int x, int y);
  fptr func;
};

int
main ()
{
  Fred f;
  f.run();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)