Delphi中“严格私有”和“受保护”访问修饰符之间的区别?

前端之家收集整理的这篇文章主要介绍了Delphi中“严格私有”和“受保护”访问修饰符之间的区别?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
但是我用Pascal语言学习编程和结构化编程之后,我开始用Delphi了解OOP.

所以,我真的不明白严格的私人教学和受保护的指令之间的区别..所以这里是我的代码,它是关于一个“包”的创作,只是介绍我的德尔福的教训,老师告诉我们如何创建对象:

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;

所以这只是对象创建的一个例子.我明白什么是公共声明(外界接近的界面),但是我看不到私有和受保护的声明有什么区别..谢谢你试图帮助我..

解决方法

私人,受保护和公共的区别是非常简单的:

私有成员/方法仅在声明它们的类中可见.
>受保护的成员/方法在类和所有子类中都是可见的.
>所有其他类都可以看到公共成员和方法.

在Delphi中有一个“bug”,使所有成员在同一个单元内公开的可见性. strict关键字纠正了这个行为,所以私有实际上是私有的,甚至在一个单元内.为了良好的封装,我建议始终使用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;
原文链接:https://www.f2er.com/delphi/102886.html

猜你在找的Delphi相关文章