虚函数与多态

说再多也不如来个小例子清楚:

#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/p/2010217.html