当前 class 成员函数的指针数组
Array of Pointers on Member functions of current class
我尝试创建当前 class 成员函数的指针数组,但暂时没有成功...
我已经尝试了很多东西,这是我的代码:
// Human.hpp
#include <iostream>
class Human
{
private:
void meleeAttack(std::string const & target);
void rangedAttack(std::string const & target);
void intimidatingShout(std::string const & target);
public:
void action(std::string const & action_name, std::string const & target);
};
// Human.cpp
#include "Human.hpp"
// ...
void Human::action(std::string const & action_name, std::string const & target)
{
std::string actionsStr[] = {"meleeAttack", "rangedAttack", "intimidatingShout"};
typedef void (Human::*Actions)(std::string const & target);
Actions actions[3] = {&Human::meleeAttack, &Human::rangedAttack, &Human::intimidatingShout};
for (int i = 2; i >= 0; i--)
if (actionsStr[i] == action_name)
{
actions[i](target); // there is an error HERE
break;
}
}
此代码在编译时产生错误:
main.cpp:41:23: error: called object type 'Actions' (aka 'void (Human::*)(const std::string &)') is not a function or function pointer
actions[i](target);
~~~~~~~~~~^
1 error generated.
有什么好的方法吗?
for (int i = 2; i >= 0; i--)
if (actionsStr[i] == action_name)
{
(this->*(actions[i]))(target);
break;
}
我尝试创建当前 class 成员函数的指针数组,但暂时没有成功...
我已经尝试了很多东西,这是我的代码:
// Human.hpp
#include <iostream>
class Human
{
private:
void meleeAttack(std::string const & target);
void rangedAttack(std::string const & target);
void intimidatingShout(std::string const & target);
public:
void action(std::string const & action_name, std::string const & target);
};
// Human.cpp
#include "Human.hpp"
// ...
void Human::action(std::string const & action_name, std::string const & target)
{
std::string actionsStr[] = {"meleeAttack", "rangedAttack", "intimidatingShout"};
typedef void (Human::*Actions)(std::string const & target);
Actions actions[3] = {&Human::meleeAttack, &Human::rangedAttack, &Human::intimidatingShout};
for (int i = 2; i >= 0; i--)
if (actionsStr[i] == action_name)
{
actions[i](target); // there is an error HERE
break;
}
}
此代码在编译时产生错误:
main.cpp:41:23: error: called object type 'Actions' (aka 'void (Human::*)(const std::string &)') is not a function or function pointer
actions[i](target);
~~~~~~~~~~^
1 error generated.
有什么好的方法吗?
for (int i = 2; i >= 0; i--)
if (actionsStr[i] == action_name)
{
(this->*(actions[i]))(target);
break;
}