示例:对象中[]算符重载多级的实现示例
示例实现:实现对对象的数组成员变量进行访问与写入---支持多维
type aa=class
data;
indList;
public
function create(v);
begin
data:=v;
indList:=array();
end;
function operator[0](index,s1); //[0]读操作,多级访问
begin
//s1<0时,最后一层
indList[length(indList)]:=index;
v:=data;
for i,ind in indList do
v:=v[ind];
if s1<0 then begin
indList:=array();
return v;
end
else
return self; //返回对象
end;
function operator[1](index,v);//[1]写操作,
begin
indList[length(indList)]:=index;
if ifnone(v) then return self; //返回对象,存在多级
sv:='data';
for i,ind in indList do
if ifstring(ind) then sv+="['"+ind+"']";
else sv+="["$ind$"]";
sv+=":=v;";
eval(&sv);
indList:=array();
end;
end;
调用测试:
t:=array(("A":1,"B":2,"C":3),("A":11,"B":22,"C":33));
a:=new aa(t);
echo a[0,"B"];
a[1,"C"]:=999;
echo tostn(a.data);
打印结果:
2
array(
("A":1,"B":2,"C":3),
("A":11,"B":22,"C":999))