Delphi:Create()构造函数末尾的访问冲突

xan*_*ngr 7 delphi delphi-xe2

我有一个非常基本和简单的类,如下所示:

装载机;

interface

uses
  Vcl.Dialogs;

type
  TLoader = Class(TObject)
  published
      constructor Create();
  end;

implementation

{ TLoader }    
constructor TLoader.Create;
begin
   ShowMessage('ok');

end;

end.
Run Code Online (Sandbox Code Playgroud)

从Form1我称之为:

procedure TForm1.Button1Click(Sender: TObject);
var
 the : TLoader;
begin
  the := the.Create;
end;
Run Code Online (Sandbox Code Playgroud)

现在,在the := the.Create部件之后,delphi显示消息,'ok'然后给我一个错误并说Project Project1.exe raised exception class $C0000005 with message 'access violation at 0x0040559d: read of address 0xffffffe4'.

它也显示了这一行:

constructor TLoader.Create;
begin
   ShowMessage('ok');

end; // <-------- THIS LINE IS MARKED AFTER THE ERROR.
Run Code Online (Sandbox Code Playgroud)

我是德尔福的新手.我正在使用Delphi XE2,我无法设法修复此错误.有没有人给我看路径或有解决方案?

And*_*and 16

var
  the : TLoader;
begin
  the := the.Create;
Run Code Online (Sandbox Code Playgroud)

是不正确的.它应该是

var
  the : TLoader;
begin
  the := TLoader.Create;
Run Code Online (Sandbox Code Playgroud)

  • 不,你不能这样做,@ Arioch.`ClassType`函数通过从给定对象读取类引用来工作.在你的建议中,`ClassType`将从未初始化的变量中读取,因为还没有有效的对象引用,这与原始问题面临的问题相同.`ClassType`是一个实例方法,所以你需要有一个实例. (5认同)
  • 你在说什么,@ Arioch?虚拟构造函数与此无关."ClassType"函数在C++ Builder中的工作方式与在Delphi中的工作方式相同; 未初始化的`the`变量上的表达式`the-> ClassType()`在C++中与在Delphi中一样错误.在C++中,您如何看待它的捷径?C++不会让你直接调用`ClasssType`返回的构造函数; 不起作用的代码不是捷径. (4认同)
  • @xangr - 别担心.这是德尔福的经典之作.我已经失去了我做过这么多次的计数. (2认同)

Mas*_*ler 5

你的语法错了.如果要构造新对象,则应在构造函数调用中使用类名,而不是变量名:

procedure TForm1.Button1Click(Sender: TObject);
var
 the : TLoader;
begin
  the := TLoader.Create;
end;
Run Code Online (Sandbox Code Playgroud)