myrtti.cpp
来自「Visual C++高级编程及其项目应用开发(含源代码)」· C++ 代码 · 共 124 行
CPP
124 行
#include <iostream>
#include <typeinfo>
using namespace std;
class Vehicle
{
public:
virtual void Move()
{
cout<<"Vehicle Move!"<<endl;
}
virtual void Stop()
{
cout<<"Vehicle Stop!"<<endl;
}
};
class Bus : public Vehicle
{
public:
void Move()
{
cout<<"Bus Move"<<endl;
}
void Stop()
{
cout<<"Bus Stop!"<<endl;
}
void ShowStation()
{
cout<<"Show the Station!"<<endl;
}
};
//void ShowClass(Vehicle *pV);
void ShowClass(Vehicle &pV);
void main()
{
//定义几个用于测试的变量
Bus bus;
Vehicle vehicle;
Vehicle *pVehicle =new Vehicle();
Bus *pBus = new Bus();
pVehicle =&bus;
Vehicle &rV =*pVehicle;
if(typeid(pVehicle)==typeid(Vehicle*))
{
pVehicle->Move(); //输出Bus Move!,这个和判断的初衷是不符合的
}
else
{
vehicle.Move();
}
cout<<typeid(*pVehicle).name()<<endl;
/****************************************************
下面的一段代码将对操作符dynamic_cast进行讲述和例解
*****************************************************/
//pVehicle->Move(); //按基类的Move()输出;
//pVehicle = &bus; //将基类指针指向派生类对象
//pVehicle->Move(); //按派生类的Move()输出,这是虚函数的作用
//dynamic_cast<Bus *>(pVehicle); //转换类型,如果没有上面的pVehicle = &bus语句
//该处将可能会出现错误。
//pVehicle->Move(); //按派生类的Move()输出
//pVehicle->ShowStation(); //该语句编译通不过
// 下面分别是强制类型转换 和 运行时刻类型转换
// 他们将产生同样的输出结果
//((Bus*)pVehicle)->ShowStation();
//dynamic_cast<Bus *>(pVehicle)->ShowStation();
// 根据上面的代码来看,强制向下类型转换和运行时刻类型转换,在功能上似乎并无太大区别。
// 其实,dynamic_cast主要是应用在运行时刻,而且,它实际上一次执行了两个操作,分别是:
// 检验转换请求是否有效 以及 发生类型转换的动作。该操作符比其他类型转换要安全,
// 因为它将在转换前进行检验。
//cout<<typeid(*pVehicle).name()<<endl; // 输出类型名Vehicle
//pVehicle =&bus;
//cout<<typeid(*pVehicle).name()<<endl; // 输出类型名Bus
//如果是内置类型使用typeid会如何呢?
//cout<<typeid(8).name()<<endl; // 输出int
//cout<<typeid(8.5).name()<<endl; // 输出double
cout<<endl;
//ShowClass(bus);
//ShowClass(vehicle);
}
/*void ShowClass(Vehicle *pV)
{
if(Bus *pb=dynamic_cast<Bus*>(pV)) //此处的等号是赋值,判断条件是指针pb是否为0
{
pb->ShowStation();
}
else
{
pV->Move();
}
}*/
void ShowClass(Vehicle &pV)
{
try
{
Bus &pb = dynamic_cast<Bus &>(pV);
pb.ShowStation();
}
catch(std::bad_cast)
{
pV.Move();
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?