需要在 Commands 中指向类中的函数。
{"clearcom", apps.clearCommandTerminal, false},
示例代码
struct Command
{
char const *text;
void (*f)(void);
bool active;
};
/* enumeration of objects - commands */
Command commands[]
{
{"clearcom", clearCommandTerminal, false},
{"dectop", desctop, true},
{"deepsleep", powerSaveDeepSleep, true},
{"systray", systemTray, true},
{"app_desctop", _desc.window("f"), true}
};
指向类中函数的指针是成员函数指针,如下所示:
// variable f points to any function in MyClass
void (MyClass::*f)(void); // you don't have to write (void) in C++ - you could also write ()
f = &MyClass::myFunc; // assign it
MyClass c;
(c.*f)(); // call it
f
指向函数MyClass::myFunc
。它也不指向 MyClass
类的实例 - 它不指向 c.myFunc
。当您调用实例时,该实例将被“添加”。
如果您想指向
c.myFunc
,则没有语言功能可以执行此操作。您可以将库中的 std::function
与 std::bind
或 lambda 函数一起使用:
std::function<void()> f;
// lambda function - anonymous function that doesn't capture anything
// (apps is a global variable)
f = []() {apps.clearCommandTerminal();};
// (if apps isn't a global variable)
f = [&apps]() {apps.clearCommandTerminal();};
// same thing with std::bind
f = std::bind(&AppsClass::clearCommandTerminal, &apps);
使用此类东西时必须小心生命周期,因为如果在
apps
被销毁后调用该函数,则可能会导致程序崩溃或执行一些奇怪的操作(未定义的行为)。