我有2点C++类的问题:传递一个类的成员函数作为函数参数
的第一个问题是:我怎样才能使这样我就可以在另一个函数&传递类成员函数作为参数我怎么才能运行/调用该功能?我怎样才能做到类静态函数。它也许更容易被看这个代码明白我的问题:
class DebuggingManager
{
string testLog;
bool test1()
{
// run test & return whether it passed or failed
}
static bool test2()
{
}
// How can I call a member function?
void catalogueTest(string testName, bool DebuggingManager::*nMemberFunction)
{
testLog += "Status of " + testName + ": " + ((*)nMemberFunction()) + "\n";
}
// How can I call a static function?
void catalogueTest(string testName, bool DebuggingManager::*nStaticFunction)
{
testLog += "Status of " + testName + ": " + DebuggingManager::nStaticFunction() + "\n";
}
// how do I pass a member function or a static function as a parameter in another function
bool runTests()
{
catalogueTest("Test of member functin", test1());
catalogueTest("Test of static functin", test2());
}
};
的第二个问题是:是否有不良(或危险)的做法调用类成员(或静态)函数间接就像上面。我有一种感觉,这是非常糟糕的C++的做法?
编辑:实施意见 感谢您的答复,我试图实现他的意见,它的很多我的头左右,虽然,这会是正确的吗?
// I have a feeling that ParameterList is incorect, would I pass the implicit obj as a parameter or is it done automatically like in normal object function calls?
typedef bool (DebuggingManager::*MemberPointerType)(ParameterList);
void catalogueTest(tstring testName, DebuggingManager* obj, MemberPointerType *nMemberFunction)
{
debugLog += _T("Status of ") + testName + _T(": ") + (obj->*nMemberFunction)() + _T("\r\n");
}
void catalogueStaticTest(tstring testName, bool DebuggingManager::nStaticFunction)
{
debugLog += _T("Status of ") + testName + _T(": ") + nStaticFunction + _T("\r\n");
}
我很惊讶,这不是已经回答也许其他人是累过,不希望查找第500次成员函数指针的语法。 –
请参阅http:// stackoverflow。com/questions/2463112 /指向ac-class-member-function-as-a-global-functions-parameter的链接http://www.parashift.com/c++-faq-lite/pointers- to-members.html在声明/使用普通和静态成员函数指针时有注意的语法和注意事项。至于是否坏,我会说:可能不是在特定情况下(如测试或其他人),但作为编写代码的日常练习并不是一件好事,因为它很棘手,并且因为对于大多数您可以使用它们的任何东西都有更好的机制。 – shelleybutterfly