所有クラスの初期化

提供: RAD Studio
移動先: 案内検索

ペンとブラシをパブリッシュに設定する への移動


コンポーネントにクラスを追加した場合、そのコンポーネントのコンストラクタでは、それらのクラスを初期化して、ユーザーが実行時にそれらのオブジェクトとやり取りできるようにする必要があります。同様に、コンポーネントのデストラクタでは、所有しているオブジェクトを破棄してからコンポーネント自身を破棄する必要があります。

図形コントロールにペンとブラシを追加したので、以下のように、図形コントロールのコンストラクタでそれらを初期化し、また、図形コントロールのデストラクタでそれらを破棄する必要があります。

  1. 図形コントロールのコンストラクタでペンとブラシのインスタンスを作成します。
constructor TSampleShape.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);                      { always call the inherited constructor }
  Width := 65;
  Height := 65;
  FPen := TPen.Create;                                               { construct the pen }
  FBrush := TBrush.Create;                                         { construct the brush }
end; 
__fastcall TSampleShape::TSampleShape(TComponent* Owner) : TGraphicControl(Owner)
{
  Width = 65;
  Height = 65;
  FBrush = new TBrush();                               // construct the pen
  FPen = new TPen();                                   // construct the brush
}
  1. オーバーライドしたデストラクタをコンポーネント クラスの宣言に追加します。

    type
      TSampleShape = class(TGraphicControl)
      public                                                  { destructors are always public}
        constructor Create(AOwner: TComponent); override;
        destructor Destroy; override;                          { remember override directive }
      end; 
    
    class PACKAGE TSampleShape : public TGraphicControl
    {
      .
      .
      .
    public:                                                // destructors are always public
        virtual __fastcall TSampleShape(TComponent* Owner);
        __fastcall ~TSampleShape();                        // the destructor
        .
        .
        .
    };
    
  2. ユニットの implementation セクションで、この新しいデストラクタを記述します。

    destructor TSampleShape.Destroy;
    begin
      FPen.Free;                                                    { destroy the pen object }
      FBrush.Free;                                                { destroy the brush object }
      inherited Destroy;                         { always call the inherited destructor, too }
    end; 
    
    __fastcall TSampleShape::~TSampleShape()
    {
      delete FPen;                                         // delete the pen object
      delete FBrush;                                       // delete the brush object
    }
    

関連項目