D-programming-class-access-modifiers

提供:Dev Guides
移動先:案内検索

Dプログラミング-クラスアクセス修飾子

データの非表示は、オブジェクト指向プログラミングの重要な機能の1つであり、プログラムの機能がクラス型の内部表現に直接アクセスできないようにします。 クラスメンバへのアクセス制限は、クラスボディ内のラベル付き publicprivate 、および protected セクションで指定されます。 キーワードpublic、private、およびprotectedは、アクセス指定子と呼ばれます。

クラスには、複数のパブリック、保護、またはプライベートのラベル付きセクションを含めることができます。 各セクションは、別のセクションラベルまたはクラス本体の右中括弧が表示されるまで有効です。 メンバーとクラスのデフォルトのアクセスはプライベートです。

class Base {

   public:

 //public members go here

   protected:

 //protected members go here

   private:

 //private members go here

};

Dのパブリックメンバー

*public* メンバーは、クラス外のどこからでも、プログラム内からアクセスできます。 次の例に示すように、メンバー関数なしでパブリック変数の値を設定および取得できます-

import std.stdio;

class Line {
   public:
      double length;

      double getLength() {
         return length ;
      }

      void setLength( double len ) {
         length = len;
      }
}

void main( ) {
   Line line = new Line();

  //set line length
   line.setLength(6.0);
   writeln("Length of line : ", line.getLength());

  //set line length without member function
   line.length = 10.0;//OK: because length is public
   writeln("Length of line : ", line.length);
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Length of line : 6
Length of line : 10

プライベートメンバー

*private* メンバー変数または関数にアクセスしたり、クラスの外部から表示することさえできません。 クラスおよびフレンド機能のみがプライベートメンバーにアクセスできます。

デフォルトでは、クラスのすべてのメンバーはプライベートです。 たとえば、次のクラスでは width はプライベートメンバーです。つまり、メンバーに明示的にラベルを付けるまで、プライベートメンバーと見なされます-

class Box {
   double width;
   public:
      double length;
      void setWidth( double wid );
      double getWidth( void );
}

実際には、次のプログラムに示すように、クラスの外部から呼び出すことができるように、プライベートセクションのデータとパブリックセクションの関連関数を定義する必要があります。

import std.stdio;

class Box {
   public:
      double length;

     //Member functions definitions
      double getWidth() {
         return width ;
      }
      void setWidth( double wid ) {
         width = wid;
      }

   private:
      double width;
}

//Main function for the program
void main( ) {
   Box box = new Box();

   box.length = 10.0;
   writeln("Length of box : ", box.length);

   box.setWidth(10.0);
   writeln("Width of box : ", box.getWidth());
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Length of box : 10
Width of box : 10

保護されたメンバー

*protected* メンバー変数または関数はプライベートメンバーに非常に似ていますが、派生クラスと呼ばれる子クラスでアクセスできるというもう1つの利点があります。

次の章で、派生クラスと継承について学習します。 今のところ、1つの子クラス SmallBox が親クラス Box から派生している次の例を確認できます。

次の例は上記の例に似ており、ここで width メンバーは派生クラスSmallBoxのメンバー関数からアクセスできます。

import std.stdio;

class Box {
   protected:
      double width;
}

class SmallBox:Box  {//SmallBox is the derived class.
   public:
      double getSmallWidth() {
         return width ;
      }

      void setSmallWidth( double wid ) {
         width = wid;
      }
}

void main( ) {
   SmallBox box = new SmallBox();

  //set box width using member function
   box.setSmallWidth(5.0);
   writeln("Width of box : ", box.getSmallWidth());
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Width of box : 5