在面向?qū)ο缶幊讨幸粋€最重要的概念就是繼承。繼承允許我們在另一個類,這使得它更容易創(chuàng)建和維護一個應(yīng)用程序來定義一個類。這也提供了一個機會重用代碼的功能和快速的實施時間。
當(dāng)創(chuàng)建一個類,而不是完全寫入新的數(shù)據(jù)成員和成員函數(shù),程序員可以指定新的類要繼承現(xiàn)有類的成員。這個現(xiàn)有的類稱為基類,新類稱為派生類。
繼承的想法實現(xiàn)是有關(guān)系的。例如,哺乳動物IS-A動物,狗,哺乳動物,因此狗IS-A動物,等等。
一個類可以從多個類中派生的,這意味著它可以繼承數(shù)據(jù)和函數(shù)從多個基類。要定義一個派生類中,我們使用一個類派生列表中指定的基類(ES)。一個類派生列表名稱的一個或多個基類和具有形式:
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()); }
當(dāng)上面的代碼被編譯并執(zhí)行,它會產(chǎn)生以下結(jié)果:
Total area: 35
派生類可以訪問它的基類的所有非私有成員。因此,基類成員,不應(yīng)該訪問的派生類的成員函數(shù)應(yīng)在基類中聲明為private。
派生類繼承了所有基類方法有以下例外:
構(gòu)造函數(shù),析構(gòu)函數(shù)和基類的拷貝構(gòu)造函數(shù)。
基類的重載運算符。
繼承可以是多級的,如下面的例子。
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()); }
讓我們編譯和運行上面的程序,這將產(chǎn)生以下結(jié)果:
Total area: 169