C++ 中的內聯虛擬函式


C++ 中的虛擬函式用於建立基類指標列表,並呼叫任何派生類的函式,而無需瞭解派生類物件的型別。虛擬函式在執行時進行後期解析。

虛擬函式的主要用途是實現執行時多型性。行內函數用於提高程式碼效率。每次呼叫行內函數時,在編譯時,行內函數的程式碼替換為行內函數呼叫點。

無論何時使用基類引用或指標呼叫虛擬函式,都不能內聯此函式,但是,如果使用不帶該類的引用或指標呼叫物件,則可以內聯,因為編譯器在編譯時知道物件的精確類。

示例程式碼

 動態演示

#include<iostream>
using namespace std;
class B {
   public:
      virtual void s() {
         cout<<" In Base \n";
      }
};

class D: public B {
   public:
      void s() {
         cout<<"In Derived \n";
      }
};

int main(void) {
   B b;
   D d; // An object of class D
   B *bptr = &d;// A pointer of type B* pointing to d
   b.s();//Can be inlined as s() is called through object of class
   bptr->s();// prints"D::s() called"
   //cannot be inlined, as virtualfunction is called through pointer.
   return 0;
}

輸出

In Base
In Derived

更新於: 2019 年 7 月 30 日

2K+ 瀏覽量

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.