Calling a non-static variable from a static function
在学习C的过程中尝试做某事时遇到问题,我不确定如何处理这种情况:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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? } }; |
任何帮助将不胜感激! :)
1 // Is there a way to do it?
编号
将其作为参数传递,使其静态或使
这里有两个可能的答案:
1.关于在静态函数中使用非静态项:
正如我们先前的问题/答案中所述,这是不可能的,除非您在静态函数中具有特定的
-
您的代码注释清楚地表明您不能在函数调用中添加
MyClass 参数; - 现有参数并不表明您已经有一个指向父类对象的指针;
- 在这种情况下使用全局对象将是不可取的。
2.关于您要执行的操作:
您似乎希望具有静态功能,因为您希望在将脚本命令映射到功能指针的表中提供该功能。
替代A
如果
替代B
使用命令设计模式修改代码设计以实现脚本引擎:它非常适合此类问题。这将需要对您的代码进行一些重构,但是之后它将变得更加可维护和可扩展!
我认为没有任何办法可以做到。原因如下:
静态成员函数未附加到任何特定对象,这意味着它无法访问非静态的其他成员,因为它们已附加到对象。
看起来您不需要使其成为静态成员。如果确定可以-则将其作为参数传递。例如,将
bool isActive();
函数,并在调用此"有问题的"函数时将其参数传递给该函数。
您还可以将成员变量更改为static,但是看起来您需要EACH对象,而不是全部使用