如何将函数从类传递到结构

问题描述 投票:0回答:1

需要在 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}
};
c++ class struct
1个回答
0
投票

指向类中函数的指针是成员函数指针,如下所示:

// 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
被销毁后调用该函数,则可能会导致程序崩溃或执行一些奇怪的操作(未定义的行为)。

© www.soinside.com 2019 - 2024. All rights reserved.