//+------------------------------------------------------------------+
//| Check_GetPointer.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| 执行列表元素的类 |
//+------------------------------------------------------------------+
class CItem
{
int m_id;
string m_comment;
CItem* m_next;
public:
CItem() { m_id=0; m_comment=NULL; m_next=NULL; }
~CItem() { Print("Destructor of ",m_id,
(CheckPointer(GetPointer(this))==POINTER_DYNAMIC)?
"dynamic":"non-dynamic"); }
void Initialize(int id,string comm) { m_id=id; m_comment=comm; }
void PrintMe() { Print(__FUNCTION__,":",m_id,m_comment); }
int Identifier() { return(m_id); }
CItem* Next() {return(m_next); }
void Next(CItem *item) { m_next=item; }
};
//+------------------------------------------------------------------+
//| 列表中最简单的类 |
//+------------------------------------------------------------------+
class CMyList
{
CItem* m_items;
public:
CMyList() { m_items=NULL; }
~CMyList() { Destroy(); }
bool InsertToBegin(CItem* item);
void Destroy();
};
//+------------------------------------------------------------------+
//| 从开始嵌入列表元素 |
//+------------------------------------------------------------------+
bool CMyList::InsertToBegin(CItem* item)
{
if(CheckPointer(item)==POINTER_INVALID) return(false);
//---
item.Next(m_items);
m_items=item;
//---
return(true);
}
//+------------------------------------------------------------------+
//| 通过删除元素删除列表 |
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- 循环工作服务指针
CItem* item;
//--- 循环检测并删除动态指针
while(CheckPointer(m_items)!=POINTER_INVALID)
{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamyc object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}
//---
}
//+------------------------------------------------------------------+
//| 脚本程序启动函数 |
//+------------------------------------------------------------------+
void OnStart()
{
CMyList list;
CItem items[10];
CItem* item;
//--- 创建并加入一个动态对象指针到列表
item=new CItem;
if(item!=NULL)
{
item.Initialize(100,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- 添加自动指针到列表
for(int i=0; i<10; i++)
{
items[i].Initialize(i,"automatic");
items[i].PrintMe();
item=GetPointer(items[i]);
if(CheckPointer(item)!=POINTER_INVALID)
list.InsertToBegin(item);
}
//--- 在列表开始添加一个以上动态对象指针
item=new CItem;
if(item!=NULL)
{
item.Initialize(200,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- 删除所有列表元素
list.Destroy();
//--- 脚本结束后所有列表元素都被删除
//--- 末端看到专家标签
}
|