我需要关于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的地址是什么?这是否可能导致"访问冲突(“Access Violation”)"?
(2) 好的,ToString()方法指向同一地址
(3) 为什么a和b有相同的类名?
(4) 好的,a和b是两个不同的变量
(5) 如果b是TClassA,为什么可以使用"MyToString" 方法?