我正在使用 Delphi XE3。在研究这篇帖子 Delphi - Maintaining Self References to an Object 之后,我明白了类类型的变量实际上是引用对象的指针。
因此,我编写了以下代码进行测试:
在我的代码中,使用PMyClass(Item)似乎也可以获取对象地址,因为Integer(PMyClass(Item))与Integer(Item)相同。然而,使用指向对象的指针似乎无法调用任何方法,P.GetName()和P ^ .GetName()都会导致访问冲突。为什么?
我的问题是,我是否可以在编程中使用类的指针。同时,是否有必要使用类的指针,因为类类型的变量已经保存了对象地址。
TMyClass = class
public
constructor Create(Name: string);
destructor Destroy;
function GetName: string;
private
FName: string;
end;
PMyClass = ^TMyClass;
constructor TMyClass.Create(Name: string);
begin
FName := Name;
end;
destructor TMyClass.Destroy;
begin
end;
function TMyClass.GetName: string;
begin
Result := FName;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Item: TMyClass;
P: PMyClass;
begin
Item := TMyClass.Create('Jim');
P := PMyClass(Item);
OutputDebugString(PWideChar(Format('Address of object: %x; Address of variable Item: %x; Value of P: %x;',
[Integer(Item), Integer(@Item), Integer(P)])));
OutputDebugString(PWideChar(Format('Name is %s', [Item.GetName()])));
OutputDebugString(PWideChar(Format('Name is %s', [P.GetName()])));
end;
在我的代码中,使用PMyClass(Item)似乎也可以获取对象地址,因为Integer(PMyClass(Item))与Integer(Item)相同。然而,使用指向对象的指针似乎无法调用任何方法,P.GetName()和P ^ .GetName()都会导致访问冲突。为什么?
我的问题是,我是否可以在编程中使用类的指针。同时,是否有必要使用类的指针,因为类类型的变量已经保存了对象地址。
NativeInt
而不是Integer
,对吧? - Andreas Rejbrand