#include<Windows.h>#include<iostream>usingnamespace std;classA{public:virtualvoidShow(){
cout <<"基类:A\n";}voidrole(){
cout <<"啥也不干!\n";}};classB:public A
{public:voidShow(){
cout <<"派生类:B\n";}voidrole(){
cout <<"哈哈哈\n";}};classC:public A
{public:voidShow(){
cout <<"派生类:C\n";}voidrole(){
cout <<"啦啦啦\n";}};intmain(void){
A a;
B b;
C c;
A* ap =&b;/****************************************************
静态类型转换:static_cast
仅当允许转换的时候,才可以用,取代隐式转换
****************************************************/
B* bp =static_cast<B*>(ap);
bp->role();system("pause");return0;}
二、重新解释:reinterpret_cast
#include<Windows.h>#include<iostream>usingnamespace std;classA{public:virtualvoidShow(){
cout <<"基类:A\n";}voidrole(){
cout <<"啥也不干!\n";}};classB:public A
{public:voidShow(){
cout <<"派生类:B\n";}voidrole(){
cout <<"哈哈哈\n";}};classC:public A
{public:voidShow(){
cout <<"派生类:C\n";}voidrole(){
cout <<"啦啦啦\n";}};intmain1(void){
A a;
B b;
C c;/****************************************************
强行转换,指鹿为马,非常危险:reinterpret_cast
能用static_cast就不要用reinterpret_cast
****************************************************/
B* bp =reinterpret_cast<B*>(&c);
bp->role();system("pause");return0;}
三、动态类型转换:dynamic_cast
#include<Windows.h>#include<iostream>usingnamespace std;classA{public:virtualvoidShow(){
cout <<"基类:A\n";}voidrole(){
cout <<"啥也不干!\n";}};classB:public A
{public:voidShow(){
cout <<"派生类:B\n";}voidrole(){
cout <<"哈哈哈\n";}};classC:public A
{public:voidShow(){
cout <<"派生类:C\n";}voidrole(){
cout <<"啦啦啦\n";}};/*******************
动态类型转换:dynamic_cast
用于基类派生类之间的转换,基类必须有虚函数(多态)
*******************/voidtest(A* a){
a->Show();
B* b =dynamic_cast<B*>(a);if(b){
b->role();}else{
C* c =dynamic_cast<C*>(a);if(c){
c->role();}else{
a->role();}}}voidtest(A& a){
a.Show();try{
B& b =dynamic_cast<B&>(a);
b.role();}catch(bad_cast bc){//cout << bc.what() << endl;try{
C& c =dynamic_cast<C&>(a);
c.role();}catch(bad_cast bc){//cout << bc.what() << endl;
a.role();}}}intmain3(void){
A a;
B b;
C c;
A* ap =&a;test(ap);
ap =&b;test(ap);
ap =&c;test(ap);
cout <<"----------------------\n";
A& Ap = a;test(Ap);
A& Bp = b;test(Bp);
A& Cp = c;test(Cp);system("pause");return0;}