虛函數

虛函數

代碼以下定義:ios

// test1107.cpp : 定義控制檯應用程序的入口點。 //  #include "stdafx.h" #include <iostream> #include <vector>
using namespace std; class father{ public: int f_age; std::string f_name; father(int a = 1,std::string n = ""):f_age(a),f_name(n){} virtual int get_age(){return f_age;} }; class son : public father{ public: int s_age; std::string s_name; son(int a = 0,std::string n = ""):s_age(a),s_name(n){} int get_age(){return s_age;} }; int main(){ father f; son s; cout<<f.get_age()<<endl; cout<<s.get_age()<<endl; system("pause"); }

輸出爲:函數

1spa

0指針

在基類中的虛函數,就是要提示用戶在派生類中要從新定義。code

當基類中的虛函數定義時,是使用指針或者引用做爲參數,那麼在運行是,要判斷傳入的參數,是基類的對象,仍是派生類的對象。對象

若是是基類的對象,則調用基類中的虛函數定義。blog

若是是派生類的對象,則調用派生類中對基類虛函數的新定義的函數。get

相關文章
相關標籤/搜索