類的訪問修飾符

數據隱藏是面向對象編程,允許防止程序的功能直接訪問類類型的內部表現的重要特徵之一。將訪問限制的類成員是由類體內標記public, private, protected。關鍵字public, private, protected被稱爲訪問訪問修飾符。

一個類可以有多個public, protected, private標記的部分。每個部分仍然有效,直至另一部分標籤或類主體的結束右大括號。成員和類的缺省訪問是私有的。

class Base { public: // public members go here protected: // protected members go here private: // private members go here };

公共成員:

公共成員是從類以外的任何地方,但在程序中訪問。可以設置和獲取公共變量的值,下面的示例中所示的任何成員函數:

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); }

當上面的代碼被編譯並執行,它會產生以下結果:

Length of line : 6
Length of line : 10

私有成員:

一個私有成員變量或函數不能被訪問,甚至從類外面看。只有類和友元函數可以訪問私有成員。

默認情況下,一個類的所有成員將是私有的,例如,在下面的類寬度是一個私有成員,這意味着直到標記一個成員,它會假設一個私有成員:

class Box { double width; public: double length; void setWidth( double wid ); double getWidth( void ); }

實際上,我們定義在公共部分私人部分和相關的功能的數據,以便它們可以從類的外部調用中所示的下列程序。

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()); }

當上面的代碼被編譯並執行,它會產生以下結果:

Length of box : 10
Width of box : 10

受保護的成員:

protected成員變量或函數是非常相似的一個私有成員,但條件是他們能在被稱爲派生類的子類來訪問一個額外的好處。

將學習派生類和繼承的下一個篇章。現在可以檢查下面的示例中,這裏已經從父類派生Box一個子類smallBox。

下面的例子是類似於上面的例子,在這裏寬度部件將是可訪問由它的派生類在smallBox的任何成員函數。

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()); }

當上面的代碼被編譯並執行,它會產生以下結果:

Width of box : 5