bAN*_*bAN 19 delphi access-modifiers
但是我学习编程,在用Pascal语言进行结构化编程之后,我开始用Delphi学习OOP.
所以,我真的不明白strict private指令和那个指令之间的区别protected.所以这是我的代码,它是关于"包"的创建,它只是我的Delphi课程的介绍,老师告诉我们如何创建对象:
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;
Run Code Online (Sandbox Code Playgroud)
所以它只是对象创建的一个例子; 我理解什么是公开声明(界面易于接受)但我不知道私有声明和受保护声明之间有什么区别..感谢您试图帮助我..
Sve*_*sli 32
private,protected和public之间的区别非常简单:
在Delphi中,存在一个"错误",使所有成员的可见性在同一单元内公开.在严格的关键字纠正这种行为,使民营实际上是私人的,即使在一个单元.为了获得良好的封装,我建议始终使用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;
Run Code Online (Sandbox Code Playgroud)
严格私有 - 仅在此类中可见和可访问.
private - 仅在此类和此类单元中可见和可访问.
protected - 与后代类中的private PLUS相同
你可以在这里阅读更多关于封装的内容和想法:http://en.wikipedia.org/wiki/Encapsulation_%28computer_science%29#Encapsulation
其他答案中缺少一种情况:private甚至strict private 其他实例的字段也可以从其类中的代码访问:
type
TSO1516493= class
strict private
A: Integer;
public
procedure ChangeOther(Param: TSO1516493);
end;
{ TSO1516493 }
procedure TSO1516493.ChangeOther(Param: TSO1516493);
begin
Param.A := -1; // accessing a strict private variable in other instance !
end;
Run Code Online (Sandbox Code Playgroud)
(这与 Java 中的行为相同。)
| 归档时间: |
|
| 查看次数: |
13895 次 |
| 最近记录: |