指向非静态成员函数的函数指针

时间:2014-08-14 02:59:12

标签: c++ function pointers

错误:

C:\testa\game.cpp|147|error: no matching function for call to 'game::register_handler(PacketFamily, PacketAction, 
<unresolved overloaded function type>)'|

这是代码的一部分,因为它太大了。

我不得不在类游戏中输入typedef handler_callback,否则其中一个将未定义为另一个。

game.h

class game
{
typedef bool (game::*handler_callback)(PacketReader  reader);
public:
bool default_handler_init (PacketReader reader);
void register_default_handlers();
void register_handler(PacketFamily family, PacketAction action,handler_callback        callback);
};

game.cpp

 void game::register_default_handlers()
{
    register_handler(PACKET_F_INIT, PACKET_A_INIT,default_handler_init);

}

void game::register_handler(PacketFamily family, PacketAction action,handler_callback     callback)
{
handlers.insert(std::make_pair(std::make_pair(family, action), callback));
}

1 个答案:

答案 0 :(得分:1)

我将OP的代码扩展为以下内容,以便编译:

class PacketReader {};
class PacketFamily {};
class PacketAction {};
const PacketFamily PACKET_F_INIT;
const PacketAction PACKET_A_INIT;

class game
{
    typedef bool (game::*handler_callback)(PacketReader  reader);
public:
    bool default_handler_init (PacketReader reader);
    void register_default_handlers();
    void register_handler(PacketFamily family, PacketAction action, handler_callback callback);
};

void game::register_default_handlers()
{
    register_handler(PACKET_F_INIT, PACKET_A_INIT, default_handler_init);
}

void game::register_handler(PacketFamily family, PacketAction action, handler_callback callback)
{
    //handlers.insert(std::make_pair(std::make_pair(family, action), callback));
}

使用命令g++ -c -Wall -std=c++11 test.cpp使用g ++进行编译会产生以下错误:

test.cpp: In member function ‘void game::register_default_handlers()’:
test.cpp:18:71: error: no matching function for call to ‘game::register_handler(const PacketFamily&, const PacketAction&, <unresolved overloaded function type>)’
     register_handler(PACKET_F_INIT, PACKET_A_INIT,default_handler_init);
                                                                   ^
test.cpp:18:71: note: candidate is:
test.cpp:13:10: note: void game::register_handler(PacketFamily, PacketAction, game::handler_callback)
     void register_handler(PacketFamily family, PacketAction action,handler_callback callback);
          ^
test.cpp:13:10: note:   no known conversion for argument 3 from ‘<unresolved overloaded function type>’ to ‘game::handler_callback {aka bool (game::*)(PacketReader)}’

无论如何,要解决此问题,请将&game::添加到register_handler的调用中:

register_handler(PACKET_F_INIT, PACKET_A_INIT,&game::default_handler_init);