W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
數(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 可以在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 變量或函數(shù)無法訪問,甚至無法從類外部進(jìn)行查看,默認(rèn)情況下,一個類的所有成員都是私有的。例如,在以下類中, 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 成員變量或函數(shù)與私有成員非常相似,但是它提供了另一個好處,即它的子類對其進(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
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: