C++中如何将带参数的成员函数存入数组及动态容器
解决类成员函数指针存入数组/动态容器的问题
问题根源
你写的代码报错,是因为类的非静态成员函数自带一个隐含的this指针,它的类型是bool (Character::*)(int),和普通函数指针bool (*)(int)完全不兼容,所以没法直接赋值。
方案1:使用类成员函数指针数组
先修正数组的声明,明确是类成员函数指针类型:
class Character { public: bool Move(int direction) { /* 动作实现 */ return true; } bool Interact(int type) { /* 动作实现 */ return true; } // 声明成员函数指针数组 bool (Character::*baseAction[2])(int) = { &Character::Move, &Character::Interact }; };
调用时必须通过类的对象或指针触发,注意语法细节:
Character robot; // 通过对象调用 (robot.*robot.baseAction[0])(1); // 执行Move(1) // 通过指针调用 Character* robotPtr = &robot; (robotPtr->*robotPtr->baseAction[1])(2); // 执行Interact(2)
嫌类型声明繁琐的话,用using简化:
class Character { public: using ActionFunc = bool (Character::*)(int); bool Move(int direction) { /* 动作实现 */ return true; } bool Interact(int type) { /* 动作实现 */ return true; } ActionFunc baseAction[2] = { &Character::Move, &Character::Interact }; };
方案2:存入std::vector/std::list动态容器
如果要用到动态容器,推荐用std::function,它能统一包装各种可调用对象,使用更灵活:
方法A:绑定具体对象(适合固定机器人实例的场景)
#include <vector> #include <functional> class Character { public: bool Move(int direction) { /* 动作实现 */ return true; } bool Interact(int type) { /* 动作实现 */ return true; } std::vector<std::function<bool(int)>> actionList; Character() { // 用std::bind绑定当前对象的成员函数 actionList.push_back(std::bind(&Character::Move, this, std::placeholders::_1)); actionList.push_back(std::bind(&Character::Interact, this, std::placeholders::_1)); } }; // 使用示例 int main() { Character robot; // 遍历执行所有动作 for (auto& action : robot.actionList) { action(1); // 给每个动作传入参数1 } return 0; }
方法B:存储成员函数指针(调用时指定对象)
如果不想提前绑定对象,也可以直接把成员函数指针存入容器:
#include <vector> class Character { public: using ActionFunc = bool (Character::*)(int); bool Move(int direction) { /* 动作实现 */ return true; } bool Interact(int type) { /* 动作实现 */ return true; } std::vector<ActionFunc> actionList = { &Character::Move, &Character::Interact }; }; // 使用示例 int main() { Character robot; for (auto func : robot.actionList) { (robot.*func)(1); // 必须通过对象调用成员函数指针 } return 0; }
内容的提问来源于stack exchange,提问作者CptHavvock
相关产品推荐
相关产品推荐

