无法绑定 c++ 中抽象类中的函数
Cannot bind function from abstract class in c++
我尝试在抽象类中使用带有虚拟纯函数的std::bind
,但是我使用设计模式调用策略,因为我想制作一个可以处理游戏之间动态切换的程序。
我听不懂语法。 这是代码:
这是我的接口类
class IGame
{
public:
virtual ~IGame(){};
virtual void move_up(INFO &info)=0;
}
顺便说一下INFO
是一个定义:
#define INFO std::pair<struct GetMap*, struct WhereAmI*>
这是我在构造函数中的控件类,我调用std::bind
调用;
class CGame
{
private:
IGame *game;
int score;
std::pair<struct GetMap*, struct WhereAmI*> info; // game information
std::vector<std::function<void(std::pair<struct GetMap*, struct WhereAmI*>&)>> ptr_move_ft; //function pointer vector
public:
CGame();
~CGame();
void return_get_map(INFO &info);
}
这是CGame
类的构造函数:
CGame::CGame()
{
game = new Snake();
this->info = std::make_pair(init_map(MAP_PATH_SNAKE,0), game->init_player());
ptr_move_ft.push_back(std::bind(&CGame::return_where_i_am, this,std::placeholders::_1)); //this work
ptr_move_ft.push_back(std::bind(&game->move_up, game, std::placeholders::_1)); //this create a error
}
所以第二个push_back
会犯这个错误:
source/CGame.cpp: In constructor ‘arcade::CGame::CGame()’:
source/CGame.cpp:131:44: error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say ‘&arcade::IGame::move_up’ [-fpermissive]
ptr_move_ft.push_back(std::bind(&game->move_up, game, std::placeholders::_1));
我该怎么办?
很抱歉我的英语和 c++ 代码很差。
问题是此行中&game->move_up
表达式:
ptr_move_ft.push_back(std::bind(&game->move_up, game, std::placeholders::_1));
此表达式尝试创建指向成员函数的指针,但这些指针未绑定到特定实例。 因此,从特定实例创建指向成员函数的指针是没有意义的,类似于尝试通过实例调用静态方法。
您应该使用 &IGame::move_up
而不是&game->move_up
.
您也可以使用 &std::decay<decltype(*game)>::type::move_up
. 优点是这个表达式会调整以匹配*game
的类型,在任何指向的类型上查找名为move_up
的实例方法。 缺点是语法有点迟钝。
(下面是一个演示,演示了这两种方法将如何生成相同的指向成员函数的指针。
相关文章:
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 将自定义函数传递到基抽象类中以延迟执行
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 抽象类和构造函数
- C++ 将一组对象传递给抽象类的成员函数
- 抽象类析构函数与继承"Shutdown"函数
- 尝试在 std::map 中插入抽象类时没有用于调用的匹配函数
- C++的抽象类继承和构造函数的问题
- C++ abort() 在函数内的抽象类对象指针调用上
- 具有继承类和函数的抽象类写入单独的向量c++
- C++ 抽象类构造函数调用
- 为什么不能将std :: async用于接收对抽象类作为参数的函数
- 抽象类和虚拟构造函数的替代方案
- 抽象类的复制构造函数中的问题
- C++ 接受对抽象类的常量引用的构造函数无法初始化 std::map
- 抽象类对象和纯虚拟析构函数
- 抽象类/函数的编译错误
- 在派生类中为抽象类函数传递附加参数