D編程 Class access modifiers

2021-09-01 11:27 更新

數(shù)據(jù)隱藏是面向?qū)ο缶幊痰闹匾瘮?shù)之一,它可以防止程序的函數(shù)直接訪問類的內(nèi)部信息。類成員的訪問限制由類主體中標(biāo)有標(biāo)簽的 public , private 和 protected 修飾符指定,成員和類的默認(rèn)訪問權(quán)限為私有。

class Base { 
  
   public: 
  
  //public members go here 
  
   protected: 
  
  //protected members go here 
  
   private: 
  
  //private members go here 
  
};

Public 公開

public 可以在class以外但在程序內(nèi)的任何位置訪問,您可以在沒有任何成員函數(shù)的情況下設(shè)置和獲取公共變量的值,如以下示例所示:

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); 
} 

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

Length of line : 6 
Length of line : 10 

Private 私有

private 變量或函數(shù)無法訪問,甚至無法從類外部進(jìn)行查看,默認(rèn)情況下,一個(gè)類的所有成員都是私有的。例如,在以下類中, width 是私有成員。

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

實(shí)際上,您需要在私有部分中定義數(shù)據(jù),并在公共部分中定義相關(guān)函數(shù),以便可以從類外部調(diào)用它們,如以下程序所示。

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()); 
} 

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

Length of box : 10 
Width of box : 10

Protected  受保護(hù)

protected 成員變量或函數(shù)與私有成員非常相似,但是它提供了另一個(gè)好處,即它的子類對(duì)其進(jìn)行訪問。

下面的示例與上面的示例相似,并且 width 成員可由其派生類SmallBox的任何成員函數(shù)訪問。

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()); 
}

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

Width of box : 5


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)