0

私はDelphiを初めて使用し、Delphi 6でコンポーネントを作成していますが、コンストラクターを実行できません:

unit MyComms1;
...
type
  TMyComms = class(TComponent)
    public
      constructor MyConstructor;
    end;
implementation

constructor TMyComms.MyConstructor;
begin
  inherited;
  ShowMessage('got here');
end;

コンストラクターが何と呼ばれるかは問題ではありませんが、このコードはコンストラクターをまったく実行しません。

編集

要求に応じて、TMyCommsクラスを初期化する方法を次に示します (このコードは、TestComms.pas という別のファイルにあります)。

unit TestComms;

interface

uses MyComms1, ...

type 
  TForm1 = class(TForm)
    MyCommsHandle = TMyComms;
    ...
    procedure BtnClick(Sender: TObject);
  private
  public
  end;
var
  Form1: TForm1;

implementation

procedure TForm1.BtnClick(Sender: TObject);
begin
  MyCommsHandle.AnotherMyCommsProcedure;
end;

編集 2

いくつかの回答を読むと、コンストラクターは Delphi で手動で呼び出す必要があるようです。これは正しいです?もしそうなら、これは確かに私の主なエラーです -__constructクラスがハンドルに割り当てられるたびに関数が自動的に呼び出されるphpに慣れています。

4

3 に答える 3

3

ほとんどの場合TMyComms.MyConstructor、異常な呼び出しおよび使用コンストラクターをテストするために呼び出しているわけではありません。でマークされた方法は、// **最も一般的な方法です。

type
  TMyComms = class(TComponent)
    public
      constructor MyConstructor;
     // the usual override;
     // constructor Create(Owner:TComponent);override; // **    
      constructor Create(AOwner:TComponent);overload; override;
      constructor Create(AOwner:TComponent;AnOtherParameter:Integer);overload;    
    end;

constructor TMyComms.Create(AOwner: TComponent);
begin
  inherited ;
  ShowMessage('got here Create');
end;

constructor TMyComms.Create(AOwner: TComponent; AnOtherParameter: Integer);
begin
  inherited Create(AOwner);
  ShowMessage(Format('got here Create with new parametere %d',[AnOtherParameter]));
end;

constructor TMyComms.MyConstructor;
begin
  inherited Create(nil);
  ShowMessage('got here MyConstructor');
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
    TMyComms.MyConstructor.Free;
    TMyComms.Create(self).Free;
    TMyComms.Create(self,1234).Free;

end;
于 2013-06-03T05:25:57.500 に答える
2

カスタム コンストラクターは呼び出されていないため、呼び出されません。

MyComm := TMyComms.MyConstructor;

しかし、コードにもエラーがあります。派生コンストラクターがないため、 simple で継承できますinherited

type
  TMyComms = class(TComponent)
    public
      constructor MyConstructor;
    end;
implementation

constructor TMyComms.MyConstructor;
begin
  inherited Create( nil ); // !
  ShowMessage('got here');
end;

inheritedカスタム コンストラクターが既存のコンストラクターと同じ名前とパラメーターを使用する場合は、simple を使用できます。

type
  TMyComms = class(TComponent)
    public
      constructor Create( AOwner : TComponent ); override;
    end;
implementation

constructor TMyComms.Create( AOwner : TComponent );
begin
  inherited; // <- everything is fine
  ShowMessage('got here');
end;
于 2013-06-03T05:28:00.633 に答える