W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
封裝是一種面向?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ù)。
在其中使用公共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 是與外界的接口,用戶需要了解它們才能使用該類。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: