gpt4 book ai didi

delphi - Delphi 中 "strict private"和 "protected"访问修饰符之间的区别?

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

但是我学习编程,在使用 Pascal 语言进行结构化编程之后,我开始使用 Delphi 学习 OOP。

所以,我真的不明白strict private指令和protected指令之间的区别。所以这是我的代码,它是关于一个“包”的创建,这只是我的Delphi类(class)的介绍,老师给我们展示了如何创建对象:

    uses
SysUtils;

Type

Tbag= class (Tobject)
strict private
FcontenM : single;
Fcontent : single;
protected
function getisempty : boolean;
function getisfull: boolean;
public
constructor creer (nbliters : single);
procedure add (nbliters : single);
procedure clear (nbliters : single);
property contenM : single read FcontenM;
property content : single read Fcontent;
property isempty : boolean read getisempty;
property isfull : boolean read getisfull;
end;


function Tseau.getisempty;
begin
result := Fcontent = 0;
end;

function Tseau.getisfull;
begin
result := Fcontent = FcontenM;
end;

constructor Tseau.creer(nbliters: Single);
begin
inherited create;
FcontenM := nbliters;
end;

procedure Tbag.add (nbliters: Single);
begin
if ((FcontenM - Fcontent) < nbliters) then fcontent := fcontenM
else Fcontent := (Fcontent + nbliters);
end;

procedure Tbag.clear (nbliters: Single);
begin
if (Fcontent > nbliters) then Fcontent := (Fcontent - nbliters)
else Fcontent := 0;
end;

所以这只是一个对象创建的例子;我理解什么是公共(public)声明(外部可访问的接口(interface)),但我不明白私有(private)声明和 protected 声明之间有什么区别。感谢您试图帮助我。

最佳答案

私有(private)、 protected 和公共(public)之间的区别非常简单:

  • 私有(private)成员/方法仅在声明它们的类中可见。
  • protected 成员/方法在类中以及所有子类中都可见。
  • 公共(public)成员和方法对所有其他类都是可见的。

在 Delphi 中,存在一个“错误”,该错误会使同一单元中所有成员的可见性公开。 strict 关键字纠正了这种行为,因此 private 实际上是私有(private)的,即使在单个单元内也是如此。为了获得良好的封装,我建议始终使用 strict 关键字。

示例代码:

type
TFather = class
private
FPriv : integer;
strict private
FStrPriv : integer;
protected
FProt : integer;
strict protected
FStrProt : integer;
public
FPublic : integer;
end;

TSon = class(TFather)
public
procedure DoStuff;
end;

TUnrelated = class
public
procedure DoStuff;
end;

procedure TSon.DoStuff;
begin
FProt := 10; // Legal, as it should be. Accessible to descendants.
FPriv := 100; // Legal, even though private. This won't work from another unit!
FStrictPriv := 10; // <- Compiler Error, FStrictPrivFather is private to TFather
FPublic := 100; // Legal, naturally. Public members are accessible from everywhere.
end;

procedure TUnrelated.DoStuff;
var
F : TFather;
begin
F := TFather.Create;
try
F.FProt := 10; // Legal, but it shouldn't be!
F.FStrProt := 100; // <- Compiler error, the strict keyword has "made the protection work"
F.FPublic := 100; // Legal, naturally.
finally
F.Free;
end;
end;

关于delphi - Delphi 中 "strict private"和 "protected"访问修饰符之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1516493/

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