一文帶你學(xué)習(xí)C++中的虛函數(shù)
概念
虛函數(shù)是一種具有特殊屬性的成員函數(shù),它可以被子類重寫,并在運(yùn)行時(shí)確定調(diào)用哪個(gè)方法。為了定義一個(gè)虛函數(shù),將在該函數(shù)的聲明中使用關(guān)鍵字virtual。當(dāng)調(diào)用一個(gè)虛函數(shù)時(shí),編譯器不會(huì)立即解析函數(shù)的調(diào)用,而是使用一個(gè)虛函數(shù)表(VTable)來(lái)查找到實(shí)際方法的地址。
語(yǔ)法
//在基類聲明中定義虛函數(shù): class Base { public: virtual void DoSomething(); }; //在子類聲明中覆蓋虛函數(shù): class Derived : public Base { public: void DoSomething() override; };
在基類中定義一個(gè)虛函數(shù)時(shí),必須在函數(shù)聲明中使用 virtual 關(guān)鍵字。如果您想其在子類中被繼承,則需要在訪問(wèn)說(shuō)明符后使用該關(guān)鍵字。在子類中覆蓋虛函數(shù)時(shí),需要使用 override 關(guān)鍵字,以幫助編譯器查找組合關(guān)系中的錯(cuò)誤。
使用
虛函數(shù)在繼承關(guān)系中非常有用。例如,如果您有一個(gè) Base 類,其中包含一個(gè)名為 DoSomething 的虛函數(shù),您希望在 Derived 類中更改 DoSomething 方法的實(shí)現(xiàn),則可以將其覆蓋為 Derived 的特定實(shí)現(xiàn)。當(dāng)您調(diào)用實(shí)際的 DoSomething 方法時(shí),虛函數(shù)表將用于查找 Derived 方法的地址,而不是 Base 方法。
示例1:調(diào)用虛函數(shù)
下面是一個(gè)簡(jiǎn)單的示例,展示如何從基類和派生類中調(diào)用虛函數(shù)。請(qǐng)注意,在這里代碼中,pBase 指向 Derived 類的實(shí)例,但是調(diào)用的是 Derived 的虛函數(shù),而不是 Base 的實(shí)際函數(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(); // 調(diào)用 Derived::DoSomething() }
輸出:
Derived DoSomething() called
示例2:使用虛函數(shù)進(jìn)行動(dòng)態(tài)綁定
下面是一個(gè)更高級(jí)的示例,演示如何使用虛函數(shù)進(jìn)行動(dòng)態(tài)綁定。假設(shè)有一個(gè) Shape 的基類,包含一個(gè)名為 Draw 的虛方法,并且有兩個(gè)派生類: Circle 和 Square。如下圖所示:
我們可以定義一個(gè)名為 draw_all 的方法,該方法將為每個(gè)形狀調(diào)用 Draw 方法。在這種情況下,我們將使用循環(huán)遍歷形狀的列表,并根據(jù)基類指針調(diào)用 Draw 方法。但是,由于 Draw 是虛的,所以它將總是委托給子類調(diào)用。
#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
總結(jié)
這篇文章介紹了C++虛函數(shù)的基本概念、語(yǔ)法、使用及其示例。虛函數(shù)是面向?qū)ο缶幊讨蟹浅V匾母拍?,常用于繼承關(guān)系中,允許子類重寫基類方法,以實(shí)現(xiàn)更多的靈活性和可復(fù)用性。通過(guò)使用虛函數(shù)表,C++可以確保在必要的時(shí)候調(diào)用正確的方法,從而提高程序的整體性能。
到此這篇關(guān)于一文詳解C++虛函數(shù)的文章就介紹到這了,更多相關(guān)C++ 虛函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章

C++類的返回值是*this的成員函數(shù)問(wèn)題

vscode使用官方C/C++插件無(wú)法進(jìn)行代碼格式化問(wèn)題

C語(yǔ)言實(shí)現(xiàn)學(xué)生宿舍信息管理系統(tǒng)課程設(shè)計(jì)

C語(yǔ)言行優(yōu)先和列優(yōu)先的問(wèn)題深入分析

C語(yǔ)言自定義數(shù)據(jù)類型的結(jié)構(gòu)體、枚舉和聯(lián)合詳解

C語(yǔ)言詳解實(shí)現(xiàn)猜數(shù)字游戲步驟