Structure have objects and cannot be copied

心不动则不痛 提交于 2019-12-24 02:24:22

问题


I'm trying to start with my first MQL4 expert advisor,

I've created a struct to handle my orders:

struct Order
  {
   int               pair;
   int               command;
   double            quantity;
   double            entry;
   double            stopLoss;
   double            profit;
   int               slippage;
   string            comment;
   int               magicNumber;
   datetime          expire;
  };

but it seems I can't do this:

  Order a;
  Order b=a;

the compiler hangs saying:

'=' - structure have objects and cannot be copied

How can I assign a struct?


回答1:


As MQL4 documentation says:

Structures that do not contain strings or objects of dynamic arrays are called simple structures; variables of such structures can be freely copied to each other, even if they are different structures. Variables of simple structures, as well as their array can be passed as parameters to functions imported from DLL.

Order is not a simple struct because of string member. So you cannot copy it with = operator. Either remove string member or copy it member by member.




回答2:



My Recommended Answer

You can use classes with pointers instead of structures, which cannot have pointers and can't copy with strings inside,

Examples are below, http://docs.mql4.com/basis/types/object_pointers

Read this to understand classes vs. structures http://docs.mql4.com/basis/types/classes


Alternative Answer with char arrays ( But simple change to this )

Define char array with a fixed size inside a structure instead of a string.

Can use
CharArrayToString( ... )
and
StringToCharArray( str, array, 0, StringLen( str ) )
to work with strings and char arrays


Example:

struct Order
  {
   int               pair;
   int               command;
   double            quantity;
   double            entry;
   double            stopLoss;
   double            profit;
   int               slippage;
   char              comment[10];
   int               magicNumber;
   datetime          expire;
  };

  Order  a;
  string str = "testing\n";

  StringToCharArray( str, a.comment, 0, StringLen( str ) );

  Order b = a;

  Comment( "Array " + CharArrayToString( b.comment ) );


来源:https://stackoverflow.com/questions/26486359/structure-have-objects-and-cannot-be-copied

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