读书笔记:const_cast,reinterpret_cast,static_cast,dynamic_cast

1、reinterpret_cast

            Allows any pointer to be converted into any other pointer type. Also allows any integral type to be converted into any pointer type and vice versa.
样例

int _tmain(int argc, _TCHAR* argv[])
{
	
	CCTest objTest;
	CCBase *p =  (CCBase*)reinterpret_cast<void*>(&objTest);

	p->SetNumber1(1);   //CCBase::SetNumber1

	CCTest *p2 =  (CCTest*)reinterpret_cast<void*>(&objTest);
	p2->SetNumber1(1);   //CCTest::SetNumber1

	unsigned int val = reinterpret_cast<unsigned int>( &objTest );  //objTest的地址

	return 0;
}

2、const_cast

              Removes the const, volatile, and __unaligned attribute(s) from a class.

样例:

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 12;
    const int& a1= a;
    const_cast<int&>(a1) =21;  // a:21,移除const常量声明
    a1 =12;                    //Error:“a1”: 不能给常量赋值
    return 0;
}

样例

class CCTest {
 public:
	 void SetNumber1(int val) const
	 {
		 const_cast<CCTest*>(this)->number = val; //ok

	 }
	 void SetNumber2(int val) const
	 {
		 number = val;              //error C3490: 由于正在通过常量对象访问“number”,因此无法对其进行修改
	 } 
 private:
	 int number;
 };


3、dynamic_cast

       可以进行两个方向转换,downcast,upcast, 也就是派生类指针转换成基类指针,也可以基类指针转换成派生类指针。如果基类指针指向的对象地址是派生类对象,那么转换指针非空,否者为NULL.

CShape *pShape1 = new CRectangle();
	try
	{
		CRectangle* p = dynamic_cast<CRectangle*>(pShape1);
	}
	catch (std::bad_cast&)
	{
		
	}
	





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值