C++中的强制类型转换 static_cast reinterpret_cast dynamic_cast const_cast


#include <iostream>
using namespace std;

class A
{
public:
	operator int() {return 1;}
	operator char * () {return NULL;}
	virtual ~A(){}
};


class B:public A
{

};

int 
main(int argc, char * argv[])
{
	A a;
	int n;
	char * p = "China Linux";
	
	/*
	static_cast用来进行自然的低风险的转换。如int型和char型之间的转换、int型与char型的转换。
	static_cast不能用来在不同类型间进行强制转换,也不能用来在整型与指针间进行转换。
	n = static_cast<int>(p); //编译错误
	p = static_cast<char *>(n); //编译错误
	*/
	n = static_cast<int>(3.14);
	n = static_cast<int>(a);
	p = static_cast<char*>(a);

	/*
	reinterpret_cast用来进行不同类型的指针与引用之间的转换。也可以用来在指针与整型数之间的转换。
	*/
	n = reinterpret_cast<int>(p);


	/*
	const_cast用来去除const属性
	*/
	const int pp = 5;
	int & b = const_cast<int&>(pp);
	b = 10;

	/*
	dynamic_cast在将基类指针转化为派生类指针时,会进行安全性检查。
	*/
	A aa;
	B * pB = dynamic_cast<B*>(&aa);
	if(pB == NULL)
		cout << "转换失败" << endl;
	return 0;
}



关于dynamic_cast,我另外测试了一下

#include <iostream> 
#include <stdexcept> 
#include <string> 
#include <vector> 
using namespace std; 

class Base{ public: virtual ~Base(){} }; 
class Derive1 : public Base{}; 
class Derive2 : public Base{}; 

int main(int argc, char * argv[]) 
{ 
    Derive1 d1; 
    Derive2 d2;    
    Derive1 * p1; 
    Derive2 * p2;    
    Base & refBase = d1; 
    Base * pBase = &d1; 
    
    p2 = dynamic_cast<Derive2*>(pBase);
    if(p2 == NULL)
        cout << "unsafe convertion" << endl;

    p1 = dynamic_cast<Derive1*>(pBase);
    if(p1 == NULL)
        cout << "unsafe convertion" << endl;

    try{
        Derive2 & ref2 = dynamic_cast<Derive2&>(refBase);
    }catch(exception & e)
    {
        cout << e.what() << endl;
    }        
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值