问题描述
我在学习C ++的过程中遇到了一个问题,我不知道如何处理这种情况:
I encountered an issue while trying to do something in the process of learning C++ and I am not sure how to handle the situation:
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?
}
};
任何帮助将非常感谢! :)
Any help would be greatly appreciated! :)
推荐答案
这里有两个潜在的答案:
There are two potential answers here:
如,这是不可能的,除非你在静态函数中有一个特定的 MyClass
object(并使用 object.isActive
)。很遗憾,您无法在此处执行此操作:
As said in our previous question/answer, this is not possible, unless you'd have in the static function a specific MyClass
object (and use object.isActive
). Unfortunately, you can't do this here :
- 您的代码注释清楚地表明您不能添加
MyClass
参数到函数调用; - 现有的参数并不表示您已经有一个指向父类对象的指针;
- 它不适合使用全局对象这样的上下文。
- your code comments clearly show that you can't add a
MyClass
parameter to the function call; - the existing parameters don't suggest that you have already a pointer to parent class object;
- it would not be adivsable to use global objects in such a context.
似乎您希望有静态函数,因为你想在一个表中提供它,脚本命令函数指针。
It seems that you want to have the function static, because you want to provide it in a table that maps script-commands to function pointers.
替代A
如果<$ c $中使用所有函数指针c> commandtable 是 MyClass
的成员,你可以想到使用指向成员函数的指针,而不是指向函数的指针。在对象上设置isActive的外部对象/函数可以将指针引用到它所知道的MyClass对象上的成员函数。
If all the function pointers used in commandtable
are members of MyClass
, you could think of using a pointer to a member function instead of a pointer to a function. The outside object/function that sets isActive on an object, could then refer the pointer to the member function, on the MyClass object it knows.
替代B
修改代码的设计以实现脚本引擎通过使用:它非常适合此类问题。这将需要一些重构你的代码,但它将是如此更加可维护和可扩展性后!
Revise the design of your code to implement your script engine by using the command design pattern: it's ideally suited for this kind of problems. It will require some refactoring of your code, but it will be so much more maintenable and extensible afterwards !
这篇关于从静态函数调用非静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!