Delphi学习之3----析构函数

来源:互联网 发布:微信砍价带支付源码 编辑:程序博客网 时间:2024/06/03 12:31


一个小程序,一个汽车类,类中方向盘类,车身类,发动机类,刹车系统类对象都是汽车类的成员,汽车类又有另外一个成员strBrand(品牌), 

 骑车类对象:ttVechile : TVechile;

方向盘类对象:ttWheel : TWheel;

发动机类对象:ttEngine : TEngine;

刹车系统类对象:ttBrakeSystem : TBrakeSystem;

品牌成员:strBrand : string;   




方向盘类 车身类 发动机类 刹车系统类都有各自的重载的Create函数,而没有重写构造函数,  汽车类有重载(overload)的构造函数,有重写(override)的析构函数,在这个过程中遇到一点问题:


0 致命错误

  犯了一个致命的低级错误:在delphi中大小写不敏感,而我在汽车类中定义成员的时候写成了如下:

  tVechile : TVechile;  tWheel : TWheel;........

  运行时 在构造函数总是报访问不可访问的地址,后来请教群里一个前辈才知道是错的,以为tVechile 和   TVehile 是一样的, 而 编译又不报错!!!   所以一定要注意!     


1 构造函数

  正确做法是:在汽车类的构造函数中调用方向盘类 车身类 发动机类 刹车系统类的构造

  //类中声明  

constructor Create(AWheelStyle : Integer; AFramework : string; ASwitch : Boolean;{TWheel}

    ABodyStyle : string; ADoors : Integer; ASkylight : Boolean;{TBody}

    AFule : string; AStroke, ACylinder, APower : Integer; ATorque : real;{TEngien}

    ABrakeSystemStyle : string; AABS : Boolean;{刹车}

    ABrand : string);  overload;


//定义

constructor TVechile.Create(AWheelStyle: Integer; AFramework: string; ASwitch: Boolean;{TWheel}

  ABodyStyle: string; ADoors: Integer; ASkylight: Boolean;  {TBody}

  AFule: string; AStroke, ACylinder, APower: Integer; ATorque: real;{TEngien}

  ABrakeSystemStyle: string; AABS: Boolean; {TBrakeSystem刹车}

  ABrand: string); 

begin

 Self.ttWheel := TWheel.Create(AWheelStyle, AFramework, ASwitch);

 Self.ttBody := TBody.Create(ABodyStyle, ADoors, ASkylight);

 Self.ttEngine := TEngine.Create(AFule, AStroke, ACylinder, APower, ATorque);

 Self.ttBrakeSystem := TBrakeSystem.Create(ABrakeSystemStyle, AABS);

 Self.strBrand := ABrand;

end;



 


2 析构函数

 正确做法:在汽车类TVechile的构造函数Destroy调用方向盘类 车身类 发动机类  刹车系统类的析构函数(默认的)


//汽车类中生民

destructor Destroy();  override;


//定义

destructor TVechile.Destroy;           //TVechile析构函数

begin


  FreeAndNil(ttWheel);

  FreeAndNil(ttBody);

  FreeAndNil(ttEngine);

  FreeAndNil(ttBrakeSystem);

end;



另外:

object.Destroy()析构时不会判断object是否为nil,这样很危险

object.Free()会判断object是否为nil,如果不是才调用Destroy

FreeAndNil(object)会先判断object是否为空,如果不为空才调用Destroy,然后将该对象object置为nil.











原创粉丝点击