C++中如何實現虛擬函式?


C++ 中的虛擬函式用於建立基類指標的列表並呼叫衍生類的方法,而無需知道具體衍生類的物件。虛擬函式在執行時被延遲解析。

以下是 C++ 程式中虛擬函式的實現 -

示例

#include <iostream>
using namespace std;
class B {
   public:
      virtual void s() { //virtual function 
         cout<<" In Base \n";
      }
};
class D: public B {
   public:
      void s() {
         cout<<"In Derived \n";
      }
};
int main(void) {
   D d; // An object of class D
   B *b= &d; // A pointer variable of type B* pointing to d
   b->s(); // prints"D::s() called"
   return 0;
}

輸出

In Derived

於以下時間更新:30-Jul-2019

632 次觀看

開啟 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.