C++基类与派生类的转换与多态性
1》首先建立一個基類Student類
頭文件Student.h 如下:
#ifndef Student_h #define Student_h #include<string> using namespace std; /* 基類Student頭文件 */ class Student{ protected:int num;string name;float score;public:Student(int num,string name,float score);void display();//******這里沒有聲明為virtual};#endif2》基類Student實現
Student.cpp
#include"Student.h" #include<iostream> Student::Student(int num, std::string name, float score){this->num=num;this->name=name;this->score=score;} void Student::display(){cout<<"num:"<<this->num<<endl;cout<<"name:"<<this->name<<endl;cout<<"score:"<<this->score<<endl;}3》派生類Graduate類頭文件
#ifndef Graduate_h #define Graduate_h #include"Student.h" /* 派生類頭文件,公有繼承Student類,并增加新屬性wage; */ class Graduate:public Student{protected:float wage;public:Graduate(int num,string name,float score,float wage);void display(); };#endif4》派生類Graduate實現
#include<iostream> #include"Graduate.h" Graduate::Graduate(int num, std::string name, float score,float wage):Student(num,name,score){this->wage=wage; }void Graduate::display(){cout<<"num:"<<this->num<<endl;cout<<"name:"<<this->name<<endl;cout<<"score:"<<this->score<<endl;cout<<"wage:"<<this->wage<<endl;}
5》測試
運行結果如下:
第二次只是輸出了派生類中相應的基類成員,而派生類中新增的數據成員“wage”沒有輸出 。
6》如何才能使其輸出呢(即實現多態性)
將基類Student類中的display函數聲明為虛函數即可:virtual void display();
再次運行就可以發現,可以利用父類的指針(p_stu)指向子類的對象(gra),通過p_stu->display()即可調用子類的display函數了。
7》這種多態性也適用于析構函數中。
上述兩個類均未給出析構函數的形式,其使用默認析構函數
當類中存在有動態分配的存儲時,該類的對象析構時也要進行回收資源。這里為了實驗,只是打印一句話。
分別在頭文件和類實現中聲明和實現該析構函數,如下:
聲明:
~Student();實現: Student::~Student(){cout<<"executing Student destructor"<<endl; }
?
聲明:
~Graduate();實現:
Graduate::~Graduate(){cout<<"executing Student destructor"<<endl;}
在Main函數中有如下語句 :
此時結果為:
可以看出,只執行了基類的析構函數,而沒有執行派生類的析構函數。原因跟之前 介紹 的display()函數調用相同。
8》如何也能執行派生類的析構函數呢?
方法與之前介紹的display函數一樣,使用虛函數,即使用虛析構函數。
將析構函數聲明為虛函數:即在前面添加Virtual即可(只需要在基類中聲明為Virtual即可,其派生類自動變為virtual)。
此時結果為:
總結
以上是生活随笔為你收集整理的C++基类与派生类的转换与多态性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Convolutional Neuron
- 下一篇: C++中变量使用前一定要初始化