面向对象编程中最重要的概念之一是继承,继承允许使用一个类继承另一个类,这样就可以直接调用父类的公共函数或变量,这使得维护变得更加容易。
子类通过":"冒号来实现继承基类。
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()); }
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()); }
Total area: 169
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Tony Bai · Go语言第一课 -〔Tony Bai〕