强制类型转换符

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值