數(shù)據(jù)隱藏是面向?qū)ο缶幊?,允許防止程序的功能直接訪問(wèn)類類型的內(nèi)部表現(xiàn)的重要特征之一。將訪問(wèn)限制的類成員是由類體內(nèi)標(biāo)記public, private, protected。關(guān)鍵字public, private, protected被稱為訪問(wèn)訪問(wèn)修飾符。
一個(gè)類可以有多個(gè)public, protected, private標(biāo)記的部分。每個(gè)部分仍然有效,直至另一部分標(biāo)簽或類主體的結(jié)束右大括號(hào)。成員和類的缺省訪問(wèn)是私有的。
class Base { public: // public members go here protected: // protected members go here private: // private members go here };
公共成員是從類以外的任何地方,但在程序中訪問(wèn)。可以設(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); }
當(dāng)上面的代碼被編譯并執(zhí)行,它會(huì)產(chǎn)生以下結(jié)果:
Length of line : 6 Length of line : 10
一個(gè)私有成員變量或函數(shù)不能被訪問(wèn),甚至從類外面看。只有類和友元函數(shù)可以訪問(wèn)私有成員。
默認(rèn)情況下,一個(gè)類的所有成員將是私有的,例如,在下面的類寬度是一個(gè)私有成員,這意味著直到標(biāo)記一個(gè)成員,它會(huì)假設(shè)一個(gè)私有成員:
class Box { double width; public: double length; void setWidth( double wid ); double getWidth( void ); }
實(shí)際上,我們定義在公共部分私人部分和相關(guān)的功能的數(shù)據(jù),以便它們可以從類的外部調(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()); }
當(dāng)上面的代碼被編譯并執(zhí)行,它會(huì)產(chǎn)生以下結(jié)果:
Length of box : 10 Width of box : 10
protected成員變量或函數(shù)是非常相似的一個(gè)私有成員,但條件是他們能在被稱為派生類的子類來(lái)訪問(wèn)一個(gè)額外的好處。
將學(xué)習(xí)派生類和繼承的下一個(gè)篇章。現(xiàn)在可以檢查下面的示例中,這里已經(jīng)從父類派生Box一個(gè)子類smallBox。
下面的例子是類似于上面的例子,在這里寬度部件將是可訪問(wèn)由它的派生類在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()); }
當(dāng)上面的代碼被編譯并執(zhí)行,它會(huì)產(chǎn)生以下結(jié)果:
Width of box : 5