一文帶你學習C++中的虛函數(shù)
概念
虛函數(shù)是一種具有特殊屬性的成員函數(shù),它可以被子類重寫,并在運行時確定調用哪個方法。為了定義一個虛函數(shù),將在該函數(shù)的聲明中使用關鍵字virtual。當調用一個虛函數(shù)時,編譯器不會立即解析函數(shù)的調用,而是使用一個虛函數(shù)表(VTable)來查找到實際方法的地址。
語法
//在基類聲明中定義虛函數(shù): class Base { public: virtual void DoSomething(); }; //在子類聲明中覆蓋虛函數(shù): class Derived : public Base { public: void DoSomething() override; };
在基類中定義一個虛函數(shù)時,必須在函數(shù)聲明中使用 virtual 關鍵字。如果您想其在子類中被繼承,則需要在訪問說明符后使用該關鍵字。在子類中覆蓋虛函數(shù)時,需要使用 override 關鍵字,以幫助編譯器查找組合關系中的錯誤。
使用
虛函數(shù)在繼承關系中非常有用。例如,如果您有一個 Base 類,其中包含一個名為 DoSomething 的虛函數(shù),您希望在 Derived 類中更改 DoSomething 方法的實現(xiàn),則可以將其覆蓋為 Derived 的特定實現(xiàn)。當您調用實際的 DoSomething 方法時,虛函數(shù)表將用于查找 Derived 方法的地址,而不是 Base 方法。
示例1:調用虛函數(shù)
下面是一個簡單的示例,展示如何從基類和派生類中調用虛函數(shù)。請注意,在這里代碼中,pBase 指向 Derived 類的實例,但是調用的是 Derived 的虛函數(shù),而不是 Base 的實際函數(shù)。
#include class Base { public: virtual void DoSomething() { std::cout << "Base DoSomething() called" << std::endl; } }; class Derived : public Base { public: void DoSomething() override { std::cout << "Derived DoSomething() called" << std::endl; } }; int main() { Derived derived; Base* pBase = &derived; pBase->DoSomething(); // 調用 Derived::DoSomething() }
輸出:
Derived DoSomething() called
示例2:使用虛函數(shù)進行動態(tài)綁定
下面是一個更高級的示例,演示如何使用虛函數(shù)進行動態(tài)綁定。假設有一個 Shape 的基類,包含一個名為 Draw 的虛方法,并且有兩個派生類: Circle 和 Square。如下圖所示:
我們可以定義一個名為 draw_all 的方法,該方法將為每個形狀調用 Draw 方法。在這種情況下,我們將使用循環(huán)遍歷形狀的列表,并根據(jù)基類指針調用 Draw 方法。但是,由于 Draw 是虛的,所以它將總是委托給子類調用。
#include?#include class Shape { public: virtual void Draw() { std::cout << "Base shape drawing" << std::endl; } }; class Circle : public Shape { public: void Draw() override { std::cout << "Circle drawing" << std::endl; } }; class Square : public Shape { public: void Draw() override { std::cout << "Square drawing" << std::endl; } }; void draw_all(const std::vector<Shape*>& shapes) { for (const auto& shape : shapes) { shape->Draw(); } } int main() { std::vector<Shape*> shapes = {new Circle(), new Square(), new Circle(), new Square()}; draw_all(shapes); }
輸出:
Circle drawing Square drawing Circle drawing Square drawing
總結
這篇文章介紹了C++虛函數(shù)的基本概念、語法、使用及其示例。虛函數(shù)是面向對象編程中非常重要的概念,常用于繼承關系中,允許子類重寫基類方法,以實現(xiàn)更多的靈活性和可復用性。通過使用虛函數(shù)表,C++可以確保在必要的時候調用正確的方法,從而提高程序的整體性能。
到此這篇關于一文詳解C++虛函數(shù)的文章就介紹到這了,更多相關C++ 虛函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C語言實現(xiàn)學生宿舍信息管理系統(tǒng)課程設計
這篇文章主要為大家詳細介紹了C語言實現(xiàn)學生宿舍信息管理系統(tǒng)課程設計,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03C語言自定義數(shù)據(jù)類型的結構體、枚舉和聯(lián)合詳解
這篇文章主要給大家介紹了關于C語言自定義數(shù)據(jù)類型的結構體、枚舉和聯(lián)合的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05