从静态函数调用非静态变量



我在学习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?
  }
};

任何帮助将不胜感激! :)

// Is there a way to do it?

不。

要么将其作为参数传递,要么将其设为静态,要么DoShowlistCommand设为非静态。

这里有两个可能的答案:

1. 关于在静态函数中使用非静态项:

正如我们在上一个问题/答案中所说,这是不可能的,除非您在静态函数中具有特定的MyClass对象(并使用object.isActive(。 不幸的是,你不能在这里这样做:

  • 您的代码注释清楚地表明您无法向函数调用添加 MyClass 参数;
  • 现有参数并不表示您已经有指向父类对象的指针;
  • 在这种情况下
  • 使用全局对象是不可接受的。

2. 关于您要做的事情:

您似乎希望函数是静态的,因为您希望在将脚本命令映射到函数指针的表中提供它。

备选方案A

如果 commandtable 中使用的所有函数指针都是 MyClass 的成员,则可以考虑使用指向成员函数的指针而不是指向函数的指针。 在对象上设置 isActive 的外部对象/函数可以将指针引用到它知道的 MyClass 对象上的成员函数。

备选案文B

使用命令设计模式修改代码设计以实现脚本引擎:它非常适合此类问题。 这将需要对代码进行一些重构,但之后它将更加易于维护和可扩展!

我认为

没有任何办法可以做到这一点。原因如下:静态成员函数不附加到任何特定对象,这意味着它无法访问其他非静态成员,因为它们附加到对象。

看起来不需要将其设置为静态成员。如果您确定这样做 - 则将其作为参数传递。例如,制作一个

bool isActive((;

函数

,并在您调用此"有问题"函数时将参数从它传递到该函数的某个地方。

您也可以将成员变量更改为静态,但看起来每个对象都需要它,而不是一劳永逸

最新更新