次の 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 クラスを定義します。元のバージョンでは、タイマーのリストを使用して呼び出しごとに別々に時間を保存しますが、コードは単純化され、最小限の作業例を提供し、実際のコンパイルの問題に焦点を当てています。
問題は、静的変数を初期化するために次の行を使用しているときです。
static Timer *_timer = new Timer(__FUNCTION__); // Line 30.
コンパイルは次のように失敗します:
「Timer」 - ローカル変数は使用できません TestProfiler.mqh 30 30
単語をドロップするstatic
と、コードは正常にコンパイルされます。
しかし、同じ関数が何度も何度も呼び出されるたびにオブジェクトを破棄したくないため、この変数をクラスへの静的ポインターとして定義したいので、私には役に立ちません。後で読むことができるリストに追加されます。MQL コンパイラが上記のコードのコンパイルを妨げる理由がよくわかりません。また、この構文は以前のビルドでも問題なく機能していたと思います。
MetaEditor 5.00 ビルド 1601 (2017 年 5 月) を使用しています。
静的変数宣言の何が問題なのですか? また、Timer クラスを指すように修正するにはどうすればよいですか?