强制类型转换符

来源:互联网 发布:淘宝永恒强袭自由高达 编辑:程序博客网 时间:2024/06/08 00:17
#include<iostream>#include<string>using namespace std;class CAnimal{public:virtual void Speak() = 0;};class CCat : public CAnimal  //继承了CAnimal,{public:void CatchMice() { cout << "Cat: I caught a mouse!" << endl; }void Speak() { cout << "Cat: Meow!" << endl; }};class Book{};class CDog : public CAnimal {public:void WagTail() { cout << "Dog: I caught a mouse!" << endl; }void Speak() { cout << "Dog: Bow-Wow!" << endl;}};void DetermineType(CAnimal* pAnimal)  //确定类型。{    CDog* pDog = dynamic_cast<CDog *>(pAnimal);//运行时的类型识别,if(pDog){         cout << "The animal is a dog?" << endl; pDog->WagTail();}CCat* pCat = dynamic_cast<CCat *>(pAnimal);if(pCat){         cout << "The animal is a cat?" << endl; pCat->CatchMice();}}int main (){   double dpi = 2.54532;   int dp = static_cast<int>(dpi);  //静态转换,将dpi的double类型转换成int类型复制给变量dp,   int dp2 = (int)dpi;  //传统C风格的转换,   int dp3 = dpi;   // 隐式转换,   cout << dp << endl;   cout << dp2 << endl;   char *ps = "Hello xiao cui ";   int *psp = reinterpret_cast<int *>(ps);//  reinterpret_cast强制类型转换,   CAnimal *pAnimal = new CCat();   CCat *pCat = static_cast<CCat *>(pAnimal);   Book *pBook = reinterpret_cast<Book *>(pAnimal);    const char *pc_str = "Hi xiao cui?";char *pc = const_cast<char *>(pc_str);//const_cast可以将一个const转化为非const类型,    return 0;}

0 0