delphi – 需要在派生类中构造函数声明后放置重载或覆盖单词吗?
发布时间:2020-12-15 04:06:46 所属栏目:大数据 来源:网络整理
导读:我有一个类层次结构,这个: typeTMatrix = class protected //... public constructor Create(Rows,Cols: Byte); //...type TMinMatrix = class(TMatrix) private procedure Allocate; procedure DeAllocate; public constructor Create(Rows,Cols: Byte); c
我有一个类层次结构,这个:
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; 确保子类的构造函数重写基类的构造函数 您还必须使子类的构造函数重写,并使基类的构造函数为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; 请注意,您还应该使析构函数覆盖. 介绍具有不同参数的构造函数 请注意,您只能使用相同的参数列表覆盖构造函数.如果子类需要具有不同参数的构造函数,并且您希望阻止直接调用基类的构造函数,则应编写: type TMyMatrix = class(TMatrix) //... public constructor Create(Rows,Cols,InitialValue: Byte); reintroduce; virtual; //... end implementation constructor TMyMatrix.Create(Rows,InitialValue: Byte); begin inherited Create(Rows,Cols); // <-- Explicitly give parameters here //... end; 我希望这会让事情更清楚……祝你好运! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |