C++几种转换类型的区别

const_cast将const对象转换成非const对象

如:

const int x=10;
//const_cast<必须是指针或者引用>
int &y=const_cast<int&>(x);


dynamic_cast将带有虚函数的基类指针转换成派生类指针

如:

// testorder.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
//class a{
//public:
// virtual void play()
// {
// cout<<"haha"<<endl;
// }
//};
//class b:public a{
//public:
// virtual void play()
// {
// cout<<"i am in b"<<endl;
// }
//};
//
//int main()
//{
//
// a *atmp=new a();
// b* btmp=new b();
// b* bttmp=dynamic_cast<b*>(atmp);
// bttmp->play();
//
// return 0;
//}


#include <iostream> 
using namespace std; 


class CBasic 

public: 
     virtual int test(){return 0;} // 一定要是 virtual 
}; 


class CDerived : public CBasic 

public: 
     virtual int test(){  cout<<"haha"<<endl;  return 1;} 
}; 


int main() 

     CBasic        cBasic; 
     CDerived    cDerived; 


     CBasic * pB1 = new CBasic; 
     CBasic * pB2 = new CDerived; 


     //dynamic cast failed, so pD1 is null. 
     CDerived * pD1 = dynamic_cast<CDerived * > (pB1);    



     //dynamic cast succeeded, so pD2 points to  CDerived object                                         
     CDerived * pD2 = dynamic_cast<CDerived * > (pB2);  
pD2->test();


     //dynamci cast failed, so throw an exception.             
//    CDerived & rD1 = dynamic_cast<CDerived &> (*pB1);    


//dynamic cast succeeded, so rD2 references to CDerived object. 
     CDerived & rD2 = dynamic_cast<CDerived &> (*pB2);    


     return 0; 
}

很奇怪,父类指针声明的时候指的是子类的对象,这样进行dynamic_cast的时候才会转换成功====================


static_cast:基本的数据类型间的转换

reinterprete_cast:最普通的用途是函数指针类型间的转换

int haha()
{
cout<<"haha"<<endl;
return 1;
}
void tt()
{


}
typedef void (*func)();
int main()
{

func fun[10];
fun[0]=reinterpret_cast<func>( haha);



return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值