99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

D編程 接口

2021-09-01 10:51 更新

接口是一種強(qiáng)制從其繼承的類(lèi)必須實(shí)現(xiàn)某些函數(shù)或變量的方式,不能在接口中實(shí)現(xiàn)函數(shù),因?yàn)樗枰诮涌诘睦^承類(lèi)中實(shí)現(xiàn)。

當(dāng)您想從一個(gè)接口繼承而該類(lèi)已經(jīng)從另一個(gè)類(lèi)繼承時(shí),則需要用逗號(hào)分隔該類(lèi)的名稱(chēng)和接口的名稱(chēng)。

讓我們看一個(gè)簡(jiǎn)單的示例,它說(shuō)明了接口的用法。

import std.stdio;

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

//Derived class
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);

   //Print the area of the object.
   writeln("Total area: ", Rect.getArea());
}

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

Total area: 35

Final 函數(shù)和 Static 函數(shù)接口

接口可以具有final和static方法,其自身應(yīng)包含對(duì)其的定義,這些函數(shù)不能被子類(lèi)覆蓋,一個(gè)簡(jiǎn)單的如下所示。

import std.stdio;

//Base class
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");
      }
}

//Derived class
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);
   
   //Print the area of the object.
   writeln("Total area: ", rect.getArea());
   rect.myfunction1();
   rect.myfunction2();
} 

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

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


以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)