D編程 封裝

2021-09-01 10:50 更新

封裝是一種面向?qū)ο蟮木幊谈拍睿鼘?shù)據(jù)和將數(shù)據(jù)操作在一起的函數(shù)綁定在一起,并且可以確保不受外界干擾,封裝導(dǎo)致了數(shù)據(jù)隱藏的重要OOP概念。

一個(gè)類可以包含 private ,protected和 public 修飾符,默認(rèn)情況下,類中定義的所有項(xiàng)目都是private私有的。如-

class Box { 
   public: 
      double getVolume() { 
         return length * breadth * height; 
      } 
   private: 
      double length;      //Length of a box 
      double breadth;     //Breadth of a box 
      double height;      //Height of a box 
};

變量的length,breadth和height為 private私有的,這意味著它們只能在Box類中訪問,這是實(shí)現(xiàn)封裝的一種方式。

要使某個(gè)類的一部分成為 public 公開的,需要 public 關(guān)鍵字修飾它,程序中的所有函數(shù)都可以訪問它修飾的所有變量或函數(shù)。

數(shù)據(jù)封裝

在其中使用公共public成員和私有private成員實(shí)現(xiàn)類的任何D程序都是數(shù)據(jù)封裝和數(shù)據(jù)抽象的一個(gè)示例。考慮以下示例-

import std.stdio;
  
class Adder { 
   public: 
      //constructor 
      this(int i=0) { 
         total=i; 
      } 
      
      //interface to outside world 
      void addNum(int number) { 
         total += number; 
      } 
      
      //interface to outside world 
      int getTotal() { 
         return total; 
      }; 
   
   private: 
      //hidden data from outside world 
      int total; 
}
 
void main( ) { 
   Adder a=new Adder(); 
   
   a.addNum(10); 
   a.addNum(20); 
   a.addNum(30);  
   writeln("Total ",a.getTotal()); 
} 

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

Total 60

上一類將數(shù)字相加,然后返回總和。公共方法 addNum 和 getTotal 是與外界的接口,用戶需要了解它們才能使用該類。


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號