C++ 多态性 1-- 父类强制转换为子类,关键字dynamic_cast

#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
     16-02 父类的强制转换 
---------------------------------*/
class father
{
public:
	void smart()
	{
		cout<<"父亲很聪明"<<endl;
	}
//	virtual void beautiful(){cout<<"父亲也很beautiful"<<endl;}
	virtual ~father(){cout<<"析构father"<<endl;}
};
class son:public father
{
public:
	virtual void beautiful(){cout<<"儿子也很帅"<<endl;}
	~son(){cout<<"析构son"<<endl;}
};
int main()
{
	father *pf;
	int choice=0;
	bool quit;
	while(1)
	{
		quit=false;
		cout<<"0)退出 1)父亲 2)儿子: ";
		cin>>choice;
		switch(choice)
		{
			case 0:
				quit=true;
				break;
			case 1:
				pf =new father;
				//pf->beautiful();
				break;
			case 2:
				pf =new son; //dynamic_cast可以对不同类之间的数据类型进行转换
				dynamic_cast<son*>(pf)->beautiful(); //它可以将一个基类的指针转换成派生类的指针
				pf->smart();
				delete pf;
				break;
			default:
				cout<<"请输入0到2之间的数字:";
				break;
		}
		if(quit)
			break;	
	}


	cout<<"程序结束"<<endl;
	return 0;
}



运行结果:

0)退出 1)父亲 2)儿子: 1
0)退出 1)父亲 2)儿子: 2
儿子也很帅
父亲很聪明
析构son
析构father
0)退出 1)父亲 2)儿子: 0
程序结束
Press any key to continue


版权声明:本文为Paulliam原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。