hug*_*rth 3 c++ pointers c++11
我在这里寻求帮助.
我的课
LevelEditor
Run Code Online (Sandbox Code Playgroud)
有这样的功能:
bool SetSingleMast(Game*, GameArea*, GameArea*, vector<IShip*>*);
bool SetDoubleMast(Game*, GameArea*, GameArea*, vector<IShip*>*);
...
Run Code Online (Sandbox Code Playgroud)
在main.cpp中,我想创建一个指向LevelEditor对象函数的指针数组.我正在做这样的事情:
bool (*CreateShips[2])(Game*, GameArea*, GameArea*, vector<IShip*>*) =
{LevelEdit->SetSingleMast, LevelEdit->SetDoubleMast, ...};
Run Code Online (Sandbox Code Playgroud)
但它给了我一个错误:
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
Run Code Online (Sandbox Code Playgroud)
我甚至不知道它是什么意思.有人能帮助我吗?
您不能使用普通函数指针指向非静态成员函数; 你需要指向成员的指针.
bool (LevelEditor::*CreateShips[2])(Game*, GameArea*, GameArea*, vector<IShip*>*) =
{&LevelEditor::SetSingleMast, &LevelEditor::SetDoubleMast};
Run Code Online (Sandbox Code Playgroud)
你需要一个对象或指针来调用它们:
(level_editor->*CreateShips[1])(game, area, area, ships);
Run Code Online (Sandbox Code Playgroud)
虽然,假设您可以使用C++ 11(或Boost),您可能会发现使用它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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |