虚函数与多态
說再多也不如來個小例子清楚:
#include "stdafx.h" #include <iostream> #include <vector>using namespace std;class CBase { public:virtual void print(){cout<<"Base::print()"<<endl;}CBase(){};~CBase(){}; };class CDerive:public CBase { public:void print(){cout<<"Derive::print()"<<endl;}CDerive(){};~CDerive(){}; };void printVector(const vector<CBase*>& vec) {vector<CBase*>::const_iterator vec_iter;for (vec_iter = vec.begin();vec_iter != vec.end();vec_iter++ ){(*vec_iter)->print();} }int _tmain(int argc, _TCHAR* argv[]) {CBase objBase;CDerive objDerive;vector<CBase*> vec;vec.push_back(&objBase);vec.push_back(&objDerive);printVector(vec);system("pause");return 0; }輸出結果:
轉載于:https://www.cnblogs.com/dahai/archive/2011/04/09/2010217.html
總結
- 上一篇: 仙居(三)
- 下一篇: 我对浮动的认识(一)