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