1.类的声明格式
Code
type
className = class [abstract | sealed] (ancestorClass)
memberList
end;
type
className = class [abstract | sealed] (ancestorClass)
memberList
end;
2.类的声明和使用
Code
//定义
type TMemoryStream = class(TCustomMemoryStream)
private
FCapacity: Longint;
procedure SetCapacity(NewCapacity: Longint);
protected
function Realloc(var NewCapacity: Longint): Pointer; virtual;
property Capacity: Longint read FCapacity write SetCapacity;
public
destructor Destroy; override;
procedure Clear;
procedure LoadFromStream(Stream: TStream);
procedure LoadFromFile(const FileName: string);
procedure SetSize(NewSize: Longint); override;
function Write(const Buffer; Count: Longint): Longint; override;
end;
//使用
var stream: TMemoryStream;
stream := TMemoryStream.Create;
//定义
type TMemoryStream = class(TCustomMemoryStream)
private
FCapacity: Longint;
procedure SetCapacity(NewCapacity: Longint);
protected
function Realloc(var NewCapacity: Longint): Pointer; virtual;
property Capacity: Longint read FCapacity write SetCapacity;
public
destructor Destroy; override;
procedure Clear;
procedure LoadFromStream(Stream: TStream);
procedure LoadFromFile(const FileName: string);
procedure SetSize(NewSize: Longint); override;
function Write(const Buffer; Count: Longint): Longint; override;
end;
//使用
var stream: TMemoryStream;
stream := TMemoryStream.Create;
3.类的继承
Code
//继承一个类
type TSomeControl = class(TControl);
//根类 TObject
type TMyClass = class
end;
//等价于
type TMyClass = class(TObject)
end;
//继承一个类
type TSomeControl = class(TControl);
//根类 TObject
type TMyClass = class
end;
//等价于
type TMyClass = class(TObject)
end;
4.基类和子类
Code
type
TFigure = class(TObject);
TRectangle = class(TFigure);
TSquare = class(TRectangle);
var
Fig: TFigure;
//the variable Fig can be assigned values of type TFigure, TRectangle, and TSquare.
type
TFigure = class(TObject);
TRectangle = class(TFigure);
TSquare = class(TRectangle);
var
Fig: TFigure;
//the variable Fig can be assigned values of type TFigure, TRectangle, and TSquare.
5.获取对象类型
Code
type objectTypeName = object (ancestorObjectType)
memberList
end;
type objectTypeName = object (ancestorObjectType)
memberList
end;
6.类的关联
Code
type
TFigure = class; // forward declaration
TDrawing = class
Figure: TFigure;
end;
TFigure = class // defining declaration
Drawing: TDrawing;
end;
type
TFigure = class; // forward declaration
TDrawing = class
Figure: TFigure;
end;
TFigure = class // defining declaration
Drawing: TDrawing;
end;