Using a member function pointer within a class

懵懂的女人 提交于 2019-11-30 07:28:31

The syntax you need looks like:

((object).*(ptrToMember)) 

So your call would be:

((*this).*(func))(foo, bar);

I believe an alternate syntax would be:

(this->*func)(foo, bar);

You need the following funky syntax to call member functions through a pointer:

(this->*func)(foo, bar);

There are two things you need to take care of. First is the declaration of the function pointer type:

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

Next is the syntax for calling the function using a pointer:

(this->*func)(foo,bar)

Here is the modified sample code that will compile and run:

#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;
}

A member function with two args is really a three arg function. 'this' is an implicit argument so the error you are getting is about missing the 'this' arg.

Non static class member functions have hidden this pointer as an argument.

I think, the syntax (this->*func)(foo,bar) is the way to make compiler understand that it need to add this to the function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!