C++中的早期繫結和延遲繫結


在這一節中,我們將瞭解 C++ 中的早期繫結和延遲繫結。繫結是指識別符號轉換為地址的過程。對於每個變數和函式,都需要進行這一繫結。對於函式,這是編譯器透過正確的函式定義匹配呼叫。可以在編譯時或執行時進行繫結。

早期繫結

這是編譯時多型性。在這裡,直接將一個地址與函式呼叫相關聯。對於函式過載,這是一個早期繫結的示例。

示例

 即時演示

#include<iostream>
using namespace std;
class Base {
   public:
   void display() {
      cout<<" In Base class" <<endl;
   }
};
class Derived: public Base {
   public:
   void display() {
      cout<<"In Derived class" << endl;
   }
};
int main(void) {
   Base *base_pointer = new Derived;
   base_pointer->display();
   return 0;
}

輸出

In Base class

延遲繫結

這是執行時多型性。在這種型別的繫結中,編譯器會新增程式碼,在執行時標識物件型別,然後透過正確的函式定義匹配呼叫。這是透過使用虛擬函式實現的。

示例

 即時演示

#include<iostream>
using namespace std;
class Base {
   public:
   virtual void display() {
      cout<<"In Base class" << endl;
   }
};
class Derived: public Base {
   public:
   void display() {
      cout<<"In Derived class" <<endl;
   }
};
int main() {
   Base *base_pointer = new Derived;
   base_pointer->display();
   return 0;
}

輸出

In Derived class

更新於:30-7-2019

14K+ 次瀏覽

開始你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.