W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
面向?qū)ο缶幊讨凶钪匾母拍钪皇抢^承,繼承允許使用一個類繼承另一個類,這樣就可以直接調(diào)用父類的公共函數(shù)或變量,這使得維護變得更加容易。
子類通過":"冒號來實現(xiàn)繼承基類。
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());
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
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());
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Total area: 169
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: