gpt4 book ai didi

delphi - 了解构造函数的可见性

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

这是两个简单的类,最初都没有关键字(virtual、overload、override、reintroduce):

TComputer = class(TObject)
public
constructor Create(Teapot: Integer);
end;

TCellPhone = class(TComputer)
public
constructor Create(Teapot: Integer; Handle: string);
end;

我将把上面的定义表示为稍微短一点的:

TComputer = class(TObject)
constructor Create(Teapot: Integer);

TCellPhone = class(TComputer)
constructor Create(Teapot: Integer; Handle: string);

在构造 TCellPhone 时,只有一个构造函数(intstring) - 因为祖先构造函数已被隐藏。我将把 TCellPhone 的可见构造函数指示为:

  • 茶壶:整数;句柄:字符串
<小时/>

现在的问题是,前 3 种情况有意义,第 4 种则不然:

1。祖先构造函数被后代隐藏:

TComputer = class(TObject)
constructor Create(Teapot: Integer);

TCellPhone = class(TComputer)
constructor Create(Teapot: Integer; Handle: string);
  • 茶壶:整数;句柄:字符串

这是有道理的,祖先构造函数被隐藏,因为我声明了一个新的构造函数。

2。祖先虚拟构造函数被后代隐藏:

TComputer = class(TObject)
constructor Create(Teapot: Integer); virtual;

TCellPhone = class(TComputer)
constructor Create(Teapot: Integer; Handle: string);
  • 茶壶:整数;句柄:字符串

这是有道理的,祖先构造函数被隐藏,因为我已经声明了一个新的构造函数。

Note: Because the ancestor is virtual: Delphi will warn you that you're hiding the virtual ancestor (in the previous example of hiding a static constructor: nobody cares, so no warning). The warning can be suppressed (meaning "Yeah yeah yeah, i'm hiding a virtual constructor. i meant to do that.") by adding reintroduce:

    TComputer = class(TObject)
constructor Create(Teapot: Integer); virtual;

TCellPhone = class(TComputer)
constructor Create(Teapot: Integer; Handle: string); reintroduce;

3。由于重载,祖先构造函数未隐藏在后代中:

TComputer = class(TObject)
constructor Create(Teapot: Integer);

TCellPhone = class(TComputer)
constructor Create(Teapot: Integer; Handle: string); overload;
  • 茶壶:整数;句柄:字符串
  • 茶壶:整数

这是有道理的,因为后代构造函数是祖先构造函数的重载,因此两者都可以存在。祖先构造函数没有被隐藏。

4。由于重载,虚拟祖先构造函数未隐藏在后代中 - 但仍然收到警告:

这种情况毫无意义:

TComputer = class(TObject)
constructor Create(Teapot: Integer); virtual;

TCellPhone = class(TComputer)
constructor Create(Teapot: Integer; Handle: string); overload;
  • 茶壶:整数;句柄:字符串
  • 茶壶:整数

    方法“Create”隐藏基类型“TComputer”的虚拟方法

这没有什么意义。不仅祖先没有隐藏,后代也重载;它甚至不应该提示。

什么给出了?

最佳答案

Delphi 的文档说:

If you overload a virtual method, use the reintroduce directive when you redeclare it in descendant classes. For example,

type
T1 = class(TObject)
procedure Test(I: Integer); overload; virtual;
end;
T2 = class(T1)
procedure Test(S: string); reintroduce; overload;
end;

如果没有重新引入指令,它仍然有效,正如您所注意到的,但您会收到警告。

此外,您实际上隐藏了 TObject.Create,但它与警告无关。如果您认为您可能还想访问 TObject.Create,请执行以下操作:

type
TComputer = class(TObject)
constructor Create(Teapot: Integer); reintroduce; overload; virtual;
end;

type
TCellPhone = class(TComputer)
constructor Create(Teapot: Integer; Handle: String); reintroduce; overload;
end;

关于delphi - 了解构造函数的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3892976/

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