gpt4 book ai didi

delphi 重载、重写、虚方法

转载 作者:行者123 更新时间:2023-12-03 15:14:09 25 4
gpt4 key购买 nike

具有如下所示的简单对象层次结构

TLiveThing=class
protected
FTest:string;
constructor Create(whereLive:string);overload;virtual;
constructor Create(haveBone:Boolean);overload;virtual;
end;

THuman=class(TLiveThing)
public
constructor Create(whereLive:string);overload;override;
constructor Create(age:integer);overload;
end;

理论上,如果我实例化 THuman,我有 2 个构造函数,但实际上 Code Insight 显示有 5 个构造函数,实际上我想看到 3 个构造函数,- 创建(whereLive:String),覆盖- 创建(年龄:整数)- 创建(haveBone:整数)

human:=THuman.Create(       <=====in there I have 5 suggestion constructor

为什么我有这种奇怪的行为?如何修复它,因为它太烦人了,我不能总是检查我需要实例化的类,如果我像下面那样实例化

human:=THuman.Create(); <===== it doesnt give me error

如何完全隐藏我的锚定构造函数? ,因为如果我像上面那样实例化,就完全给了我一个错误的对象

更新:我也可以看到默认的 Create,不带来自 TObject 的参数

最佳答案

不把重点放在错误的构造函数实现上,

你的问题是祖先类和子类都在同一个单元中定义,因此 Private/Protected 的标准定义在这里不适用。

如果您想防止祖先构造函数(您在子类中重写)在实例化该派生类的对象时显示为代码参数,那么只需将其设为 strict 的成员 严格私有(private)部分。

以你的例子:

TLiveThing=class
strict protected
constructor Create(whereLive:string); virtual;
end;

THuman=class(TLiveThing)
public
constructor Create(whereLive:string); overload; override;
constructor Create(age:integer); overload;
end;

这将阻止祖先构造函数 Create(whereLive:string)当您创建子类的实例时,不会显示为参数。

正如 David 所指出的,这与隐藏默认的 Create 构造函数无关,它仅适用于隐藏自定义构造函数。

关于delphi 重载、重写、虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16746397/

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