#include "stdafx.h"
#include <iostream.h>
class Base
{
public:
Base() { cout<<"Base Constructor."<<endl;}
~Base() { cout<<"Base Destructor."<<endl;} //做标记
virtual void textOut()
{
cout<< "This is Base!"<<endl;
} //基类虚函数
void BaseMakeASound()
{
cout<< "Meow!"<<endl;
} //基类独有函数
};
class Surface : public Base
{
public:
Surface() { cout<<"Surface Constructor."<<endl;}
~Surface() { cout<< "Surface Destructor."<<endl;}//做标记
virtual void textOut()
{
cout<<"This is Surface!"<<endl;
} //派生类函数
void SurfaceMakeASound()
{
cout<<"Quak!"<<endl;
} //派生类独有方法
};
int main(int argc, char* argv[])
{
Surface surf; //定义派生类对象
surf.textOut();
surf.BaseMakeASound(); //第一次查看派生类能否调用基类独有方法.
((Base*)&surf)->textOut(); //查看如果将派生类转换至基类后会调用哪个函数.
surf.BaseMakeASound(); //第二次查看派生类能否调用基类独有方法.
Base base; //定义基类对象
base.textOut();
((Surface*)&base)->textOut();
//查看基类对象能否转换成派生类象并调用派生类的输出函数.
((Surface*)&base)->SurfaceMakeASound();
//查看转换是否成功.必须进行显示转换
return 0;
}
执行结果:
从执行结果看出((Base*)&surf)->textOut(); 调用的是基类的函数,((Surface*)&base)->textOut();调用的是派生类的函数.说明基类和派生类对象可以互相转换并调用彼此的虚函数,如果要从基类调用派生类的独有函数需要进行显示转换.