數(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);
}
更多建議: