将功能指针分配给功能指针

Jor*_*ell 1 c++ struct pointers function-pointers

尝试在结构中将函数指针分配给函数指针时遇到问题。

我有一个struct command,它包含一个调用字符串值,一条消息以确认其激活以及一个在激活时要调用的函数。

但是,我在下面的结构的构造函数中分配函数指针时遇到麻烦(可能稍后将结构变成一个类,不确定)。

struct Command
{
    Command(string _code, string _message, void *_func(void))
        : code(_code), message(_message) { /* ERROR: */ func = _func; }

    string code;        // The string that invokes a console response
    string message;     // The response that is printed to acknowledge its activation
    void *func(void);   // The function that is run when the string is called
};
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,标/* ERROR: */有的错误出现了"expression must be a modifiable value"。我怎样才能解决这个问题?我只想将对函数的引用传递给该结构。

Snp*_*nps 5

@Joachim Pileborg所述,您无需声明指向函数的指针。

要声明函数指针,您需要在星号和标识符部分周围加上括号,例如

// 'func' is a pointer to function taking parameter void and returning void.
void (*func)(void);
Run Code Online (Sandbox Code Playgroud)

从C ++ 11开始,您还可以像这样声明一个函数指针,它不那么简洁:

std::add_pointer_t<void()> func;

std::add_pointer_t<void(int, int)> func; // Pointer to func taking 2 ints.
Run Code Online (Sandbox Code Playgroud)