我试图将一个类的非静态成员函数作为参数传递给另一个采用函数引用的成员函数。我目前的代码可以说明为:
bool someClass::baseFunction( unsigned argument, bool (&argumentFunction)(unsigned) ) const{
...
... use argumentFunction(argument) somehow...
...
}
bool someClass::anotherFunction(unsigned) const{
...
}
bool someClass::finalFunction(unsigned argument) const{
return baseFunction(argument, anotherFunction);
}
然而这会提示编译错误
"invalid use of non-static member function"
,我理解这是因为我在“finalFunction”中作为参数传递的函数是非静态的。但是,是否有任何其他方法可以将非静态成员函数作为我在此处显示的代码中的参数传递?
最佳答案
如果您要在与调用成员函数的对象相同的对象上调用成员函数,那么一个简单的指向成员的指针应该可以解决问题:
bool someClass::anotherFunction(unsigned int) { /* ... */ }
bool someClass::baseFunction(
unsigned int argument,
bool (someClass::* mf)(unsigned int) const) const {
return (this->*mf)(argument);
}
bool someClass::finalFunction(unsigned argument) {
return baseFunction(argument, &someClass::anotherFunction);
}
关于c++ - 将非静态成员函数作为参数传递给成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49733809/