指向成员函数的指针映射:无法将 void (*) 转换为 void (对象::*)

Map of pointer to member functions : cannot convert void (*) to void (Object::*)

本文关键字:void 对象 转换 函数 成员 指针 映射      更新时间:2023-10-16

>尝试将函数添加到指向成员函数映射的指针时出错。

#include <map>
#include <utility>
class Server {
protected:
    typedef void (*ScriptFunction)(std::pair<std::string, std::string>);
    std::map<std::string, ScriptFunction> internalScriptMap;
    void checkUserLogin(std::pair<std::string, std::string> packet) {}
    void handleUserCommand(std::pair<std::string, std::string> packet) {}
public:
    void setupServerInternalCommands() {
        internalScriptMap["login"] = &Server::checkUserLogin;
        internalScriptMap["clientcmd"] = &Server::handleUserCommand;
    }
};

代码板 说 (http://codepad.org/JZHeJSPz) :

t.cpp: In member function 'void Server::setupServerInternalCommands()':
Line 13: error: cannot convert 'void (Server::*)(std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >)' to 'void (*)(std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >)' in assignment
compilation terminated due to -Wfatal-errors.

我不明白为什么我的代码不想编译,为什么编译器无法将"void (*)"转换为"void(服务器::*)"。

感谢您的帮助!

你应该使用:-

typedef void (Server::*ScriptFunction)(std::pair<std::string, std::string>);

即指向成员函数的指针而不是指向函数的指针。

因为它们不兼容。成员函数指针和函数指针在标准方面是不同的。