指向成员函数的指针映射:无法将 void (*) 转换为 void (对象::*)
Map of pointer to member functions : cannot convert void (*) to void (Object::*)
>尝试将函数添加到指向成员函数映射的指针时出错。
#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>);
即指向成员函数的指针而不是指向函数的指针。
因为它们不兼容。成员函数指针和函数指针在标准方面是不同的。
相关文章:
- C++ - 非静态 void* 成员,指向具有相同地址但不同值的不同对象的另一个非静态成员
- 如何成功地将函数对象(或lambda)传递给trackbar回调的第二个参数(void*)
- 错误:为什么"void*"不是指向对象的指针类型,即使指针设置为对象?
- 对象的地址 - void* 和 void**
- C++:我可以在 void 函数中实例化对象吗?
- 称为对象类型"void (B::*)(int)"不是函数或函数指针
- 通过void指针通过C ABI传递C++对象(可能具有多个虚拟继承)
- 错误:无法在没有对象的情况下调用成员函数'void Fortest::run()'|
- 使用多线程处理对象数组 - 无效使用 void 表达式错误
- void*不是一个指向对象类型的指针 - void **的铸造错误
- 不能在没有对象的情况下调用成员函数'virtual void ThreadBase::doTask()'
- 错误:“void*”不是指向对象的指针类型
- 访问 C 中保存C++对象的 void 指针的内容
- 在C++中将(void**)转换为对象
- 使用 void 指针分配对象数组
- const void*对象初始化问题C++
- 如何检查 void* 是否指向对象类型的有效实例上的指针
- 将 C++ 对象强制转换为 void* 的安全/标准方法
- 指向成员函数的指针映射:无法将 void (*) 转换为 void (对象::*)
- 正在取消引用类型化的void*对象指针