我正在尝试创建一个带有成员函数的对象,该成员函数像这样调用另一个成员函数
foo foo1 = new foo(1, 2);
foo1.print(printj);
我有课:
class foo
{
public:
foo(int x, int y) {i = x; j = y;};
void const print(void const f());
void const printi();
void const printj();
private:
int i;
int j;
}
我的实现是这样的:
void const foo::printi(){
std::cout << i;
}
void const foo::printj(){
std::cout << j;
}
void const foo::print(void const f()){
f();
}
我得到一个错误 [错误] 没有匹配函数来调用 'foo::print()'
为什么会这样,我该如何解决?
最佳答案
你需要:
- 这样声明指向成员函数的参数:
void const print(void const (foo::*f)());
- 正确传递成员函数指针:
foo1.print(&foo::printj);
- 用实际实例调用它(成员函数调用需要一个实例):
void const foo::print(void const (foo::*f)()){
(this->*f)();
}
或者,您可以将实例作为附加参数或使用 std::bind
或 boost::bind
将它们绑定(bind)在一起。
关于具有 Unresolved 重载调用成员函数的 C++ 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40725197/