为什么在这里SIGSEGV例外

时间:2019-06-26 05:26:30

标签: user-interface delphi exception lazarus freepascal

我正在尝试下面的代码来创建一个简单的GUI应用程序:

program RnTFormclass;
{$mode objfpc}
uses
    {$IFDEF UNIX}{$IFDEF UseCThreads}
      cthreads,
    {$ENDIF}{$ENDIF}
    Interfaces, Forms, StdCtrls;

type
    RnTForm = class(TForm)
    private
        wnd: TForm;
        btn: TButton;
    public
        constructor create;
        procedure showit; 
    end; 

constructor RnTForm.create;
    begin
        Application.Initialize;
        wnd := TForm.Create(Application);
        with wnd do begin
            Height  := 300;
            Width   := 400;
            Position:= poDesktopCenter;
            Caption := 'LAZARUS WND';
            end;
        btn := TButton.Create(wnd);
            with btn do begin
            SetBounds(0, 0, 100, 50);
            Caption := 'Click Me';
            Parent  := wnd;
            end;
    end;

procedure RnTForm.showit;
    begin
        wnd.ShowModal; {Error at this line: Throws exception External: SIGSEGV }
    end;

var 
    myform1: RnTForm; 
begin
    myform1.create; 
    myform1.showit; 
end.

但是,它引发了异常,如上面代码中的注释所述。问题在哪里,如何解决?

1 个答案:

答案 0 :(得分:2)

myform1.Create应该是myform1 := RnTForm.Create

在上面的代码中,myform1nil指针(由于它是全局变量,因此被初始化为nil),直到您为其分配了某些内容,在这种情况下(指向a)RnTForm的新实例。

当然,如果myform1nil指针,则不能像确实指向对象一样使用它(因此myform1.showit将不起作用)。