D语言接口

D语言接口 首页 / D语言入门教程 / D语言接口

接口是一种强制从其继承的类必须实现某些函数或变量的方式,不能在接口中实现函数,因为它需要在接口的继承类中实现。

当您想从一个接口继承而该类已经从另一个类继承时,则需要用逗号分隔该类的名称和接口的名称。

让我们看一个简单的示例,它说明了接口的用法。

import std.stdio;

//基类
interface Shape {
   public: 
      void setWidth(int w);
      void setHeight(int h);
}

//派生类
class Rectangle: Shape {
   int width;
   int height;
   
   public:
      void setWidth(int w) {
         width=w;
      }
      void setHeight(int h) {
         height=h; 
      }
      int getArea() {
         return (width * height);
      }
}

void main() {
   Rectangle Rect=new Rectangle();
   Rect.setWidth(5);
   Rect.setHeight(7);

   //打印对象的面积。
   writeln("Learnfk Total area: ", Rect.getArea());
}

编译并执行上述代码后,将产生以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/d-programming/d-programming-interfaces.html

来源:LearnFk无涯教程网

Learnfk Total area: 35

Final 函数和 Static 函数接口

接口可以具有finalstatic方法,其自身应包含对其的定义,这些函数不能被子类覆盖,一个简单的如下所示。

import std.stdio;

//基类
interface Shape {
   public:
      void setWidth(int w);
      void setHeight(int h);
      
      static void myfunction1() {
         writeln("This is a static method");
      }
      final void myfunction2() {
         writeln("This is a final method");
      }
}

//派生类
class Rectangle: Shape {
   int width;
   int height; 
   
   public:
      void setWidth(int w) {
         width=w;
      }
      void setHeight(int h) {
         height=h;
      }
      int getArea() {
         return (width * height);
      }
}

void main() {
   Rectangle rect=new Rectangle();

   rect.setWidth(5);
   rect.setHeight(7);
   
   //打印对象的面积。
   writeln("Learnfk Total area: ", rect.getArea());
   rect.myfunction1();
   rect.myfunction2();
} 

编译并执行上述代码后,将产生以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/d-programming/d-programming-interfaces.html

来源:LearnFk无涯教程网

Learnfk Total area: 35 
This is a static method 
This is a final method

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

教程推荐

AI 音视频创作入门课 -〔唐子轩〕

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

徐昊 · TDD项目实战70讲 -〔徐昊〕

PyTorch深度学习实战 -〔方远〕

如何落地业务建模 -〔徐昊〕

说透芯片 -〔邵巍〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

SRE实战手册 -〔赵成〕

微服务架构核心20讲 -〔杨波〕

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