我需要澄清一下 Delphi 类型转换
我写了一个包含两个类的示例:TClassA 和 TClassB,TClassB 派生自 TClassA。
代码如下:
program TEST;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TClassA = class(TObject)
public
Member1:Integer;
constructor Create();
function ToString():String; override;
end;
type
TClassB = class(TClassA)
public
Member2:Integer;
constructor Create();
function ToString():String; override;
function MyToString():String;
end;
{ TClassA }
constructor TClassA.Create;
begin
Member1 := 0;
end;
function TClassA.ToString: String;
begin
Result := IntToStr(Member1);
end;
{ TClassB }
constructor TClassB.Create;
begin
Member1 := 0;
Member2 := 10;
end;
function TClassB.MyToString: String;
begin
Result := Format('My Values is: %u AND %u',[Member1,Member2]);
end;
function TClassB.ToString: String;
begin
Result := IntToStr(Member1) + ' - ' + IntToStr(Member2);
end;
procedure ShowInstances();
var
a: TClassA;
b: TClassB;
begin
a := TClassA.Create;
b := TClassB(a); // Casting (B and A point to the same Memory Address)
b.Member1 := 5;
b.Member2 := 150; // why no error? (1)
Writeln(Format('ToString: a = %s, a = %s',[a.ToString,b.ToString])); // (2)
Writeln(Format('Class Name: a=%s, b=%s',[a.ClassName,b.ClassName])); // (3)
Writeln(Format('Address: a=%p, b=%p',[@a,@b])); // (4)
Writeln(b.MyToString); // why no error? (5)
readln;
end;
begin
try
ShowInstances;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
程序输出为:
ToString: a = 5, a = 5
Class Name: a=TClassA, b=TClassA
Address: a=0012FF44, b=0012FF40
My Values is: 5 AND 150
(1) Member2 地址是什么?这是一个可能的“访问冲突”吗?
(2) ok,ToString() 方法指向同一个地址
(3) 为什么a 和b 有相同的ClassName?
(4) 好的,a 和 b 是两个不同的变量
(5) 如果 b 是 TClassA,为什么可以使用“MyToString”方法?