2013-05-03 132 views
3

我在这里寻找帮助。指向类函数的指针

我的课

LevelEditor 

具有的功能是这样的:

bool SetSingleMast(Game*, GameArea*, GameArea*, vector<IShip*>*); 
bool SetDoubleMast(Game*, GameArea*, GameArea*, vector<IShip*>*); 
... 

在main.cpp中,我想使指针关卡编辑器对象的函数的数组。我在做这样的事情:

bool (*CreateShips[2])(Game*, GameArea*, GameArea*, vector<IShip*>*) = 
{LevelEdit->SetSingleMast, LevelEdit->SetDoubleMast, ...}; 

但它给我一个错误:

error C2440: 'initializing' : cannot convert from 'overloaded-function' to 
'bool (__cdecl *)(Game *,GameArea *,GameArea *,std::vector<_Ty> *)' 
with 
[ 
    _Ty=IShip * 
] 
None of the functions with this name in scope match the target type 

我甚至不知道这是什么意思。有人能帮助我吗?

+5

指向函数的指针与指向_member_函数的指针不同。我建议你阅读['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)和['std :: bind'](http:// en。 cppreference.com/w/cpp/utility/functional/bind) – 2013-05-03 11:56:17

+0

你不能有指向特定对象函数的指针,而是指向类的函数(方法) - “LevelEditor :: SetSingleMast”。 – 2013-05-03 11:56:25

+2

并使用typedef! – jrok 2013-05-03 11:56:46

回答

6

您不能使用普通函数指针指向非静态成员函数;您需要的是指向成员的指针。

bool (LevelEditor::*CreateShips[2])(Game*, GameArea*, GameArea*, vector<IShip*>*) = 
{&LevelEditor::SetSingleMast, &LevelEditor::SetDoubleMast}; 

,你需要一个对象或指针调用他们:

(level_editor->*CreateShips[1])(game, area, area, ships); 

虽然,假设你可以使用C++ 11(或升压),你可能会发现它更易于使用std::function来包装任何类型的可调用类型:

using namespace std::placeholders; 
std::function<bool(Game*, GameArea*, GameArea*, vector<IShip*>*)> CreateShips[2] = { 
    std::bind(&LevelEditor::SetSingleMast, level_editor, _1, _2, _3, _4), 
    std::bind(&LevelEditor::SetDoubleMast, level_editor, _1, _2, _3, _4) 
}; 

CreateShips[1](game, area, area, ships); 
+0

非常感谢,我会尝试这个并使用typedef。 – hugerth 2013-05-03 12:05:05