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

时间:2014-11-26 16:53:27

标签: c++

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

#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;
    }
};

CodePad说(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.

我不明白为什么我的代码不想编译,为什么编译器无法转换&#39; void(*)&#39; to&#39; void(Server :: *)&#39;。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

你应该使用: -

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

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

答案 1 :(得分:0)

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