指向类组合中成员函数的指针

Pointer to Member Function in Class Composition

本文关键字:函数 指针 成员 组合      更新时间:2023-10-16

我有两个类,FooBar。类Foo包含称为b的类Bar的实例,并且类Bar需要访问类Foo的成员函数FooFunc。函数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)’

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

代替:

     b.BarFunc(FooFunc);

用途:

     b.BarFunc(&Foo::FooFunc);