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

80 篇文章 0 订阅
#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值