
- 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 程式設計 - 繼承
面向物件程式設計中最重要的概念之一是繼承。繼承允許根據另一個類來定義類,這使得建立和維護應用程式更容易。這也提供了重用程式碼功能和加快實現時間的機會。
建立類時,程式設計師無需編寫全新的資料成員和成員函式,而是可以指定新類應該繼承現有類的成員。這個現有類稱為**基類**,新類稱為**派生類**。
繼承的概念實現了“是-a”關係。例如,哺乳動物是動物,狗是哺乳動物,因此狗也是動物,以此類推。
D 語言中的基類和派生類
一個類可以從多個類派生,這意味著它可以繼承多個基類的資料和函式。要定義派生類,我們使用類派生列表來指定基類。類派生列表命名一個或多個基類,其形式為:
class derived-class: base-class
考慮一個基類**Shape**及其派生類**Rectangle**,如下所示:
import std.stdio; // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; } // Derived class class Rectangle: Shape { public: int getArea() { return (width * height); } } void main() { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. writeln("Total area: ", Rect.getArea()); }
編譯並執行上述程式碼後,將產生以下結果:
Total area: 35
訪問控制和繼承
派生類可以訪問其基類所有非私有成員。因此,基類成員如果不需要被派生類的成員函式訪問,應該在基類中宣告為私有。
派生類繼承所有基類方法,但以下情況除外:
- 基類的建構函式、解構函式和複製建構函式。
- 基類的過載運算子。
多層繼承
繼承可以有多個層次,以下示例展示了這一點。
import std.stdio; // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; } // Derived class class Rectangle: Shape { public: int getArea() { return (width * height); } } class Square: Rectangle { this(int side) { this.setWidth(side); this.setHeight(side); } } void main() { Square square = new Square(13); // Print the area of the object. writeln("Total area: ", square.getArea()); }
編譯並執行上述程式碼後,將產生以下結果:
Total area: 169
廣告