我有两个班级,Foo
和Bar
。类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)’
答案 0 :(得分:3)
与衰减为函数指针的非成员函数不同,非static
成员函数不会衰减为指针。
而不是:
b.BarFunc(FooFunc);
使用:
b.BarFunc(&Foo::FooFunc);