指向类函数数组的指针
Pointer to array of class functions
我在这里寻求帮助。
我班上LevelEditor
的函数如下:
bool SetSingleMast(Game*, GameArea*, GameArea*, vector<IShip*>*);
bool SetDoubleMast(Game*, GameArea*, GameArea*, vector<IShip*>*);
...
在main.cpp中,我想创建一个指向LevelEditor对象函数的指针数组。我正在做这样的事情:
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
我甚至不知道这是什么意思。有人能帮帮我吗?
不能使用普通的函数指针指向非静态成员函数;而需要指向成员的指针。
bool (LevelEditor::*CreateShips[2])(Game*, GameArea*, GameArea*, vector<IShip*>*) =
{&LevelEditor::SetSingleMast, &LevelEditor::SetDoubleMast};
,你需要一个对象或指针来调用它们:
(level_editor->*CreateShips[1])(game, area, area, ships);
但是,假设您可以使用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);
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空