che*_*r89 7 delphi inheritance constructor
我有一个类层次结构,这个:
type
TMatrix = class
protected
//...
public
constructor Create(Rows, Cols: Byte);
//...
type
TMinMatrix = class(TMatrix)
private
procedure Allocate;
procedure DeAllocate;
public
constructor Create(Rows, Cols: Byte);
constructor CreateCopy(var that: TMinMatrix);
destructor Destroy;
end;
Run Code Online (Sandbox Code Playgroud)
如您所见,派生类和基类构造函数都具有相同的参数列表.我从派生的一个显式调用基类构造函数:
constructor TMinMatrix.Create(Rows, Cols: Byte);
begin
inherited;
//...
end;
Run Code Online (Sandbox Code Playgroud)
是否有必要在Delphi中显式调用基类构造函数?可能是我需要放置重载或覆盖以清除我打算做什么?我知道如何在C++中实现它 - 只有当你想要传递一些参数时才需要显式调用基类构造函数 - 但我在Delphi编程方面没有多少经验.
onn*_*odb 14
据我所知,这里有两个不同的问题:
您必须显式调用基类的构造函数:
constructor TMinMatrix.Create(Rows, Cols: Byte);
begin
inherited;
//...
end;
Run Code Online (Sandbox Code Playgroud)
您还必须创建子类的构造函数override和基类的构造函数virtual,以确保编译器看到两者之间的关系.如果你不这样做,编译器可能会警告你TMinMatrix的构造函数"隐藏"了TMatrix的构造函数.所以,正确的代码是:
type
TMatrix = class
protected
//...
public
constructor Create(Rows, Cols: Byte); virtual; // <-- Added "virtual" here
//...
type
TMinMatrix = class(TMatrix)
private
//...
public
constructor Create(Rows, Cols: Byte); override; // <-- Added "override" here
constructor CreateCopy(var that: TMinMatrix);
destructor Destroy; override; // <-- Also make the destructor "override"!
end;
Run Code Online (Sandbox Code Playgroud)
请注意,您还应该制作析构函数override.
请注意,您只能使用相同的参数列表覆盖构造函数.如果子类需要具有不同参数的构造函数,并且您希望阻止直接调用基类的构造函数,则应编写:
type
TMyMatrix = class(TMatrix)
//...
public
constructor Create(Rows, Cols, InitialValue: Byte); reintroduce; virtual;
//...
end
implementation
constructor TMyMatrix.Create(Rows, Cols, InitialValue: Byte);
begin
inherited Create(Rows, Cols); // <-- Explicitly give parameters here
//...
end;
Run Code Online (Sandbox Code Playgroud)
我希望这会让事情更清楚......祝你好运!