
- D 程式設計基礎
- D 程式設計 - 首頁
- D 程式設計 - 概覽
- D 程式設計 - 環境
- D 程式設計 - 基本語法
- D 程式設計 - 變數
- D 程式設計 - 資料型別
- D 程式設計 - 列舉
- D 程式設計 - 字面量
- D 程式設計 - 運算子
- D 程式設計 - 迴圈
- D 程式設計 - 條件語句
- D 程式設計 - 函式
- D 程式設計 - 字元
- D 程式設計 - 字串
- D 程式設計 - 陣列
- D 程式設計 - 關聯陣列
- D 程式設計 - 指標
- D 程式設計 - 元組
- D 程式設計 - 結構體
- D 程式設計 - 聯合體
- D 程式設計 - 範圍
- D 程式設計 - 別名
- D 程式設計 - Mixin
- D 程式設計 - 模組
- D 程式設計 - 模板
- D 程式設計 - 不可變
- D 程式設計 - 檔案 I/O
- D 程式設計 - 併發
- D 程式設計 - 異常處理
- D 程式設計 - 合約
- D - 條件編譯
- D 程式設計 - 面向物件
- D 程式設計 - 類與物件
- D 程式設計 - 繼承
- D 程式設計 - 過載
- D 程式設計 - 封裝
- D 程式設計 - 介面
- D 程式設計 - 抽象類
- D 程式設計 - 有用資源
- D 程式設計 - 快速指南
- D 程式設計 - 有用資源
- D 程式設計 - 討論
D 程式設計 - 類訪問修飾符
資料隱藏是面向物件程式設計的重要特性之一,它允許防止程式的函式直接訪問類型別的內部表示。對類成員的訪問限制由類體內的標記為public、private和protected的部分指定。關鍵字 public、private 和 protected 稱為訪問說明符。
一個類可以有多個 public、protected 或 private 標記的部分。每個部分都保持有效,直到遇到另一個部分標籤或類體內的右花括號。成員和類的預設訪問許可權為 private。
class Base { public: // public members go here protected: // protected members go here private: // private members go here };
D 中的公共成員
public成員可以從類外部但在程式內部的任何地方訪問。您可以設定和獲取公共變數的值,而無需任何成員函式,如下例所示:
示例
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
私有成員
private成員變數或函式不能從類外部訪問,甚至不能檢視。只有類和友元函式可以訪問私有成員。
預設情況下,類的所有成員都是私有的。例如,在以下類中,width是一個私有成員,這意味著在您顯式標記成員之前,它被假定為私有成員:
class Box { double width; public: double length; void setWidth( double wid ); double getWidth( void ); }
實際上,您需要在 private 部分定義資料,在 public 部分定義相關函式,以便可以從類外部呼叫它們,如下面的程式所示。
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成員變數或函式與私有成員非常相似,但它提供了一個額外的優勢,即它們可以在稱為派生類的子類中訪問。
您將在下一章學習派生類和繼承。現在,您可以檢視以下示例,其中一個子類SmallBox派生自父類Box。
以下示例類似於上述示例,並且此處width成員可被其派生類 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
d_programming_classes_objects.htm
廣告