#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 continueC++ 多态性 1-- 父类强制转换为子类,关键字dynamic_cast
最新推荐文章于 2025-10-31 16:49:32 发布
本文通过一个简单的 C++ 程序演示了如何使用 dynamic_cast 进行父类到子类的安全类型转换,并展示了虚函数的多态性。程序包括一个父类 father 和一个继承自父类的子类 son,通过 dynamic_cast 对父类指针进行转换以调用子类的特定成员函数。

3764

被折叠的 条评论
为什么被折叠?



