C++ 学习之旅(16)——虚函数与纯虚函数virtual
生活随笔
收集整理的這篇文章主要介紹了
C++ 学习之旅(16)——虚函数与纯虚函数virtual
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
關于虛函數的概念講解,可以看這篇文章:
https://blog.csdn.net/siwuxie095/article/details/71159414
以下用例子進行實際說明:
#include <iostream> using namespace std;class Shape { public:int width, height;Shape(int a = 0, int b = 0){width = a;height = b;}void area(){cout << "Parent class has no area" << endl;} };class Rectangle : public Shape { public:Rectangle(int a = 0, int b = 0) :Shape(a, b) { }void area(){cout << "Rectangle class area :" << width * height << endl;} };class Triangle : public Shape { public:Triangle(int a = 0, int b = 0) :Shape(a, b) { }void area(){cout << "Triangle class area :" << width * height / 2 << endl;} };int main() {Shape* sha1 = new Shape(10, 5);Rectangle* rec = new Rectangle(10, 5);Triangle* tri = new Triangle(10, 5);sha1->area();rec->area();tri->area();cin.get();return 0; }我們有形狀類Shape,它有兩個子類:Rectangle矩形類和Triangle三角形類。
利用多態的思想,我們希望在對不同對象下達相同指令(計算面積)的時候,不同對象可以根據自身情況完成該指令。即如果是Shape類則沒有面積,而矩形和三角形各自都有計算面積的公式,以上代碼看似是可以實現的,運行結果如下:
但是,這種情況實際上只是根據實例化時所屬的類選擇不同的area方法,屬于靜態多態,如果出現以下情況:
輸出卻為:“Parent class has no area”
明明sha2指向的地址是矩形類的地址,但是卻因為實例化時用了Shape類,而導致無法正確計算面積,此時就有必要引入動態多態了。只需在Shape類中的area函數前加上virtual關鍵字即可:
#include <iostream> using namespace std;class Shape { public:int width, height;Shape(int a = 0, int b = 0){width = a;height = b;}virtual void area(){cout << "Parent class has no area" << endl;} };class Rectangle : public Shape { public:Rectangle(int a = 0, int b = 0) :Shape(a, b) { }void area(){cout << "Rectangle class area :" << width * height << endl;} };class Triangle : public Shape { public:Triangle(int a = 0, int b = 0) :Shape(a, b) { }void area(){cout << "Triangle class area :" << width * height / 2 << endl;} };int main() {Shape* sha1 = new Shape(10, 5);Rectangle* rec = new Rectangle(10, 5);Triangle* tri = new Triangle(10, 5);sha1->area();rec->area();tri->area();Shape* sha2 = rec;sha2->area();cin.get();return 0; }輸出結果如下:
而如果我們在基類中不能對虛函數給出有意義的實現,這個時候就會用到純虛函數。只需把函數體改為= 0即可:
注意此時我們無法實例化Shape類,因為它已經變成了抽象類,是作為一種規范,或者說接口而存在的。基類中定義了純虛函數,子類必須對它進行定義,否則也是無法實例化的。
輸出結果如下:
總結
以上是生活随笔為你收集整理的C++ 学习之旅(16)——虚函数与纯虚函数virtual的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《仙剑奇侠传》捆绑包 Steam 秋促史
- 下一篇: 《铁拳 8》PC 配置要求公布:推荐 R