What is the correct way to define MQL4 “#import of static class methods”?

 ̄綄美尐妖づ 提交于 2021-02-08 02:16:31

问题


What I'm trying to achieve is define classes (using MQL4) in separate files and use the methods from those classes in the main code. Essentially importing static class member functions.

 class example{                                            // ____ in example.mq4
   public:
   static void myfunction(void) export { .. do something .. }
 }

 class example{                                            // ____ in example.mqh
   public:
   static void myfunction(void);
 }

 #include <example.mqh>                                    // ____ in main.mq4:
 #import "example.ex4"
     void example::myfunction(void);
 #import

Results in a compile error when using the function as follows:

void OnInit(){
   example::myfunction();
}

compiler error:

myfunction: function must have a body

(note example.mq4 is compiled to example.ex4 and can be imported ok)


回答1:


"new"-MQL4 syntax is evolving

for the indicated purpose,

the class definition syntax shall be enough, upon instantiation of a class, its public methods are possible to be invoked on instance-objects.

Compile-time syntax:

Exporting a function without it's class-inheritance ( taking together the whole class container ) does not fit the OOP concept. This is clearly visible in the OnInit() call, where your code attempts to call a function, which is in fact a class-based object-method at a moment, where there has not yet been instantiated any object, on which the method ought to be performed anObjectINSTANCE.aClassOrInstanceMETHOD().

So, just #include

class example{                                            // ____ in example.mqh

   public:
   static void myfunction() { .. do something; }

  }

// ----------------------------                          // ____ in main.mq4
#property strict            // "new"-MQL4

#include <example.mqh>      // include

example anObject;           // create a globally visible instance

// ----------------------------
void OnInit(){
     anObject.myfunction(); // request <anObject> to perform <myfunction> method on self

     return( EMPTY );       // "new"-MQL4 insists on return even on void fun()
  }


来源:https://stackoverflow.com/questions/29469159/what-is-the-correct-way-to-define-mql4-import-of-static-class-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!