类成分中指向成员函数的指针

时间:2015-12-28 05:08:50

标签: c++ function class

我有两个班级,FooBar。类Foo包含名为Bar的类b的实例,类Bar需要访问类FooFunc的成员函数Foo。函数FooFunc执行一些算术,但是现在我只想尝试传递它,但我似乎无法使下面的MWE(名为scratch.cpp)工作:

#include <iostream>

class Foo;  // forward declaration

class Bar
{
public:
  Bar() {}
  void BarFunc(double (Foo::*func)(double))
  {
    std::cout << "In BarFunc \n";
  }
};

class Foo  // must be declared after Bar, else incomplete type
{
public:
  Foo() {}
  Bar b;

  double FooFunc(double x)
  {
    return x + 1;
  }
  void CallBarFunc()
  {
    b.BarFunc(FooFunc);  // error occurs here
  }
};

int main()
{
  Foo f;
  f.CallBarFunc();
}

我得到的错误是

scratch.cpp:27:22: error: no matching function for call to ‘Bar::BarFunc(<unresolved overloaded function type>)’
scratch.cpp:27:22: note: candidate is:
scratch.cpp:9:8: note: void Bar::BarFunc(double (Foo::*)(double))
scratch.cpp:9:8: note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘double (Foo::*)(double)’

1 个答案:

答案 0 :(得分:3)

与衰减为函数指针的非成员函数不同,非static成员函数不会衰减为指针。

而不是:

     b.BarFunc(FooFunc);

使用:

     b.BarFunc(&Foo::FooFunc);