为什么子类对象不可以传递给父类的变量?该如何处理
为什么子类对象不可以传递给父类的变量?
TTest1 = class
end;
TTest2 = class(TTest1)
end;
procedure TestFun(var Test: TTest1);
begin
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Test1: TTest1;
Test2: TTest2;
begin
Test1 := TTest1.Create;
Test2 := TTest2.Create;
Test1 := Test2; //这里可以
TestFun(Test2); //这里编译出错:Types of actual and formal var parameters must be identical
end;
------解决方案--------------------
TO : 楼上的(楼主)
类对象的变量名字本来就是一个地址。 Test1 := Test2;时,只是把Test1指向了Test2,并没有“复制”一个对象。
还是因为“类对象的变量名字本来就是一个地址”,所以procedure TestFun(Test: TTest1);就已经是传址了,不会在过程内部生成一个对象的副本。
------解决方案--------------------
procedure OpenForm(FormClass: TCRMFormClass; var FormName; InitCode: string);
begin
TCRMForm(FormName) := FormClass.CRMCreate(Application, InitCode);
TCRMForm(FormName).Show;
// others
end;
TTest1 = class
end;
TTest2 = class(TTest1)
end;
procedure TestFun(var Test: TTest1);
begin
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Test1: TTest1;
Test2: TTest2;
begin
Test1 := TTest1.Create;
Test2 := TTest2.Create;
Test1 := Test2; //这里可以
TestFun(Test2); //这里编译出错:Types of actual and formal var parameters must be identical
end;
------解决方案--------------------
TO : 楼上的(楼主)
类对象的变量名字本来就是一个地址。 Test1 := Test2;时,只是把Test1指向了Test2,并没有“复制”一个对象。
还是因为“类对象的变量名字本来就是一个地址”,所以procedure TestFun(Test: TTest1);就已经是传址了,不会在过程内部生成一个对象的副本。
------解决方案--------------------
procedure OpenForm(FormClass: TCRMFormClass; var FormName; InitCode: string);
begin
TCRMForm(FormName) := FormClass.CRMCreate(Application, InitCode);
TCRMForm(FormName).Show;
// others
end;