#pragma once class helloA { public: helloA(void); ~helloA(void); virtual void func()const{printf("A");} };helloB.h
#pragma once #include "helloa.h" class helloB : public helloA { public: helloB(void); ~helloB(void); void func()const{printf("B");} };handel.cpp
#include "stdafx.h" #include "helloA.h" #include "helloB.h" #include <vector> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<helloA> vec; helloA a; helloB b; vec.push_back(a); vec.push_back(b); for ( vector<helloA>::iterator iter=vec.begin();iter!=vec.end();iter++) { (*iter).func(); } return 0; }运行的结果:
vector<helloA*> vec; helloA *a = new helloA; helloB *b = new helloB; vec.push_back(a); vec.push_back(b); for ( vector<helloA*>::iterator iter=vec.begin();iter!=vec.end();iter++) { (*iter)->func(); }
#pragma once class helloA { public: helloA(void); ~helloA(void); virtual void func()const{printf("A");} virtual helloA* clone() const {return new helloA(*this);} };helloB.h
#pragma once #include "helloa.h" class helloB : public helloA { public: helloB(void); ~helloB(void); void func()const{printf("B");} virtual helloB* clone() const{return new helloB(*this);} };同时,添加sample类,记得把sample.cpp的代码注释掉,我们只在sample头文件更改代码即可。
#pragma once #include "helloA.h" #include "helloB.h" #include <stddef.h> class sample { public: sample():p(0),use(1){}; sample(const helloA& a):p(a.clone()),use(1){}; sample(const sample&i):p(i.p),use(i.use){use++;} ~sample(){decr_use();}; sample& operator = (const sample& i) { use++; decr_use(); p = i.p; use = i.use; return *this; } const helloA *operator->() const {if (p)return p;} const helloA &operator*() const{if(p)return *p;} private: helloA* p; size_t use; void decr_use(){if (-use == 0)delete p;} };回到main函数,更改代码
// handle.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "helloA.h" #include "helloB.h" #include "sample.h" #include <vector> #include <list> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<sample> vec; helloA a; helloB b; sample sample1(a); sample sample2(b); vec.push_back(sample1); vec.push_back(sample2); for ( vector<sample>::iterator iter=vec.begin();iter!=vec.end();iter++) { (*iter)->func(); } return 0; }运行结果: