【问题标题】:How to define a static pointer to a class in MQL?如何在 MQL 中定义指向类的静态指针?
【发布时间】:2018-01-15 02:24:30
【问题描述】:

我有以下 MQL 代码:

class Collection {
  public: void *Get(void *_object) { return NULL; }
};

class Timer      {
  protected:
    string name;
    uint start, end;
  public:
    void Timer(string _name = "") : name(_name) { };
    void TimerStart() { start = GetTickCount(); }
    void TimerStop()  { end = GetTickCount();   }
};

class Profiler {
  public:
    static Collection *timers;
    static ulong min_time;
    void Profiler()  { };
    void ~Profiler() { Deinit(); };
    static void Deinit() { delete Profiler::timers; };
};

// Initialize static global variables.
Collection *Profiler::timers = new Collection();
ulong Profiler::min_time = 1;

void main() {
  // Define local variable.
  static Timer *_timer = new Timer(__FUNCTION__); // This line doesn't.
  //Timer *_timer = new Timer(__FUNCTION__); // This line works.

  // Start a timer.
  ((Timer *) Profiler::timers.Get(_timer)).TimerStart();
  /* Some code here. */
  // Stop a timer.
  ((Timer *) Profiler::timers.Get(_timer)).TimerStop();
}

它定义了一个 Timer 类,该类用作计时器来分析函数花费了多长时间。 original version 使用一个计时器列表来分别存储每次调用的时间,但是,代码已被简化以提供最小的工作示例并专注于实际的编译问题。

问题是当我使用以下行来初始化静态变量时:

static Timer *_timer = new Timer(__FUNCTION__); // Line 30.

编译失败:

'Timer' - 不能使用局部变量 TestProfiler.mqh 30 30

当我删除static 字时,代码编译正常。

但这对我没有帮助,因为我想将此变量定义为指向类的静态指针,因为我不想每次一遍又一遍地调用同一个函数时销毁我的对象,所以计时器可以添加到以后可以读取的列表中。我真的不明白为什么 MQL 编译器会阻止编译上述代码。我也相信这种语法在以前的版本中运行良好。

我正在使用 MetaEditor 5.00 build 1601(2017 年 5 月)。

我的静态变量声明有什么问题,我该如何纠正它,使它可以指向一个 Timer 类?

【问题讨论】:

    标签: pointers compiler-errors static mql5


    【解决方案1】:

    关键字static 在 MQL4/5 中有两种不同的含义:它表示一个类的成员是静态的(这很明显),它还表示一个变量是静态的......例如,如果你有仅在一个函数中使用的变量,您可能不需要全局声明它,而是将其声明为静态变量。您可以在 mql5.com 上关于新柱的文章中找到具有 static datetime lastBar=0;isNewBar() 函数示例。此类函数中的此关键字表示该变量在函数完成后不会被删除,而是保留在内存中并用于下一次调用。如果您需要 OnTick() 函数中的变量 - 将其设置为静态没有意义,请在全局范围内声明它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2011-11-21
      • 2019-03-14
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      相关资源
      最近更新 更多