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

时间:2016-02-15 16:50:04

标签: c++ function pointers static

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

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

3 个答案:

答案 0 :(得分:3)

// Is there a way to do it?

没有

将其作为参数传递,将其设为静态,或使DoShowlistCommand为非静态。

答案 1 :(得分:2)

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

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

  

bool isActive();

函数,当你调用这个'有问题的'函数时,将一个参数从它传递给那个函数。

您也可以将您的成员变量更改为静态,但看起来您需要它用于EACH对象,而不是一对一

答案 2 :(得分:1)

这里有两个可能的答案:

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

our previous question/answer中所述,这是不可能的,除非你在静态函数中有一个特定的MyClass对象(并使用object.isActive)。不幸的是,你不能在这里做到这一点:

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

2。关于你想要做什么:

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

备选方案A

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

备选方案B

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