一道关于继承和多态的题目

#include<iostream>
#include <complex>

using namespace std;
//----------------------------------------------
class Base//基类
{
public:
	virtual void f(int);
	virtual void f(double);
	virtual void g(int i=10);
};

void Base::f(int)
{
	cout<<"Base::f(int)"<<endl;
}

void Base::f(double)
{
	cout<<"Base::f(double)"<<endl;
}

void Base::g(int i)
{
	cout<<i<<endl;
}
//------------------------------------------------

class Dervived:public Base
{
public:
	void f(complex<double>);
	void g(int i=20);
};

void Dervived::f(complex<double>)
{
	cout<<"Dervived::f(complex<double>)"<<endl;
}

void Dervived::g(int i)
{
	cout<<i<<endl;
}
//----------------------------------------------
void main()
{
	Base b;
	Dervived d;
	Base *pb=new Dervived; 
	b.f(1.0);//基类对象调用,执行基类的函数
	d.f(1.0);//子类对象调用,执行子类的函数
	pb->f(1.0);//基类的指针,指向子类,调用函数时,执行基类的函数
	b.g();//基类对象调用,执行子类的函数
	d.g();//子类对象调用,执行子类的函数
	pb->g();//基类的指针,指向子类,调用函数时,执行基类的函数
	delete pb;
}
posted @ 2011-04-08 08:54  瓜蛋  阅读(321)  评论(0编辑  收藏  举报