面向对象编程中最重要的概念之一是继承,继承允许使用一个类继承另一个类,这样就可以直接调用父类的公共函数或变量,这使得维护变得更加容易。
子类通过":"冒号来实现继承基类。
class derived-class: base-class
考虑如下基类 Shape 及其派生类 Rectangle -
import std.stdio; //基类 class Shape { public: void setWidth(int w) { width=w; } void setHeight(int h) { height=h; } protected: int width; int height; } //派生类 class Rectangle: Shape { public: int getArea() { return (width * height); } } void main() { Rectangle Rect=new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); //打印对象的面积。 writeln("Total area: ", Rect.getArea()); }
编译并执行上述代码后,将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/d-programming/d-programming-inheritance.html
来源:LearnFk无涯教程网
Total area: 35
继承可以具有多个级别,并在以下示例中显示。
import std.stdio; //基类 class Shape { public: void setWidth(int w) { width=w; } void setHeight(int h) { height=h; } protected: int width; int height; } //派生类 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); //打印对象的面积。 writeln("Total area: ", square.getArea()); }
编译并执行上述代码后,将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/d-programming/d-programming-inheritance.html
来源:LearnFk无涯教程网
Total area: 169
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)