我在尝试学习C ++的过程中遇到了一个问题,我不知道如何处理这种情况:
class Command
{
public:
const char * Name;
uint32 Permission;
bool (*Handler)(EmpH*, const char* args); // I do not want to change this by adding more arguments
};
class MyClass : public CommandScript
{
public:
MyClass() : CommandScript("listscript") { }
bool isActive = false;
Command* GetCommands() const
{
static Command commandtable[] =
{
{ "showlist", 3, &DoShowlistCommand } // Maybe handle that differently to fix the problem I've mentioned below?
};
return commandtable;
}
static bool DoShowlistCommand(EmpH * handler, const char * args)
{
// I need to use isActive here for IF statements but I cannot because
// DoShowlistCommand is static and isActive is not static.
// I cannot pass it as a parameter either because I do not want to
// change the structure of class Command at all
// Is there a way to do it?
}
};
任何帮助将不胜感激! :)
答案 0 :(得分:3)
// Is there a way to do it?
没有
将其作为参数传递,将其设为静态,或使DoShowlistCommand
为非静态。
答案 1 :(得分:2)
我认为没有办法做到这一点。原因如下: 静态成员函数未附加到任何特定对象,这意味着它无法访问非静态的其他成员,因为它们附加到对象。
看起来你不需要让它成为静态成员。如果您确定要这样做 - 那么将其作为参数传递。例如,制作一个
bool isActive();
函数,当你调用这个'有问题的'函数时,将一个参数从它传递给那个函数。
您也可以将您的成员变量更改为静态,但看起来您需要它用于EACH对象,而不是一对一
答案 2 :(得分:1)
这里有两个可能的答案:
如our previous question/answer中所述,这是不可能的,除非你在静态函数中有一个特定的MyClass
对象(并使用object.isActive
)。不幸的是,你不能在这里做到这一点:
MyClass
参数; 似乎您希望将函数设置为static,因为您希望在将脚本命令映射到函数指针的表中提供它。
备选方案A
如果commandtable
中使用的所有函数指针都是MyClass
的成员,您可以考虑使用指向成员函数的指针而不是指向函数的指针。在对象上设置isActive的外部对象/函数可以将指针引用到它知道的MyClass对象上的成员函数。
备选方案B
使用command design pattern修改代码设计以实现脚本引擎:它非常适合此类问题。它需要对您的代码进行一些重构,但之后它将更加可维护和扩展!