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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章