gpt4 book ai didi

delphi - 我需要在派生类的构造函数声明之后放置重载或覆盖字吗?

转载 作者:行者123 更新时间:2023-12-03 14:49:40 24 4
gpt4 key购买 nike

我有一个类层次结构,这个:

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;

正如您所看到的,派生类和基类构造函数都具有相同的参数列表。我从派生类显式调用基类构造函数:

constructor TMinMatrix.Create(Rows, Cols: Byte);
begin
inherited;
//...
end;

Delphi中是否需要显式调用基类构造函数?我可能需要重载或覆盖来清除我打算做什么?我知道如何在 C++ 中做到这一点 - 仅当您想向基类构造函数传递一些参数时才需要显式调用它 - 但我在 Delphi 编程方面没有太多经验。

最佳答案

据我所知,这里有两个单独的问题:

确保子类的构造函数调用基类的构造函数

您必须显式调用基类的构造函数:

constructor TMinMatrix.Create(Rows, Cols: Byte);
begin
inherited;
//...
end;

确保子类的构造函数覆盖基类的构造函数

必须使子类的构造函数重写和基类的构造函数虚拟,以确保编译器会看到两者之间的关系。如果您不这样做,编译器可能会警告您 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;

请注意,您还应该让析构函数覆盖

引入具有不同参数的构造函数

请注意,您只能覆盖具有相同参数列表的构造函数。如果子类需要具有不同参数的构造函数,并且您希望防止直接调用基类的构造函数,则应该编写:

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;

我希望这能让事情变得更清楚......祝你好运!

关于delphi - 我需要在派生类的构造函数声明之后放置重载或覆盖字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/360597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com