D语言继承

D语言继承 首页 / D语言入门教程 / D语言继承

面向对象编程中最重要的概念之一是继承,继承允许使用一个类继承另一个类,这样就可以直接调用父类的公共函数或变量,这使得维护变得更加容易。

基类和子类

子类通过":"冒号来实现继承基类。

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

AI大模型之美 -〔徐文浩〕

Tony Bai · Go语言第一课 -〔Tony Bai〕

性能优化高手课 -〔尉刚强〕

Spark性能调优实战 -〔吴磊〕

深度学习推荐系统实战 -〔王喆〕

.NET Core开发实战 -〔肖伟宇〕

Swift核心技术与实战 -〔张杰〕

从0打造音视频直播系统 -〔李超〕

许式伟的架构课 -〔许式伟〕

好记忆不如烂笔头。留下您的足迹吧 :)