概念
類型轉換的含義是通過改變一個變量的類型爲別的類型從而改變該變量的表示方式。爲了類型轉換一個簡單對象爲另一個對象你會使用類型轉換操作符。
C風格的強制類型轉換(Type Cast)很簡單,不管什麼類型的轉換統統是:TYPE b = (TYPE)a
C++風格的類型轉換提供了4種類型轉換操作符來應對不同場合的應用。
類型 | 用法 |
---|---|
static_cast | 一般的轉換 |
dynami_cast | 通常在基類和派生類之間轉換時使用 |
const_cast | 主要針對const的轉換 |
reinterpert_cast | 用於進行沒有任何關聯之間的轉換,比如一個字符指針轉換爲一個整型數 |
代碼:
#include<iostream>
using namespace std;
class Building{};
class Animal{};
class Cat :public Animal{};
//static_cast
void test01(){
int a = 97;
char c = static_cast<char>(a);
cout << "c = " << c << endl;//輸出ASCII值 a
//基礎數據類型的指針
int *p = NULL;
//char* sp = static_cast<char*>(p);//error
//對象指針
Building* building = NULL;
//Animal* ani = static_cast<Animal*>(building);//error
//轉換具有繼承關係的對象指針
//父類指針轉子類指針
Animal* ani = NULL;
Cat* cat = static_cast<Cat*>(ani);//ok
//子類指針轉換爲父類指針
Cat* soncat = NULL;
Animal* anifather = static_cast<Animal*>(soncat);//ok
Animal aniobj;
Animal& aniref = aniobj;
Cat& cat2 = static_cast<Cat&>(aniref);//ok
Cat catobj;
Cat& catref = catobj;
Animal& anifather2 = static_cast<Animal&>(catref);//ok
/*static_cast 用於內置的數據類型,
還有具有繼承關係的指針或引用*/
}
//dynamic_cast 轉換具有繼承關係的指針或引用,在轉換前會進行對象類型檢查
void test02()
{
//基礎數據類型 不能轉換
int a = 10;;
//char c = dynamic_cast<char>(a);//error
//非繼承關係的指針
Animal* ani = NULL;
//Building* building = dynamic_cast<Building*>(ani);//error
//具有繼承關係指針
//Animal* ani = NULL;
//Cat* cat = dynamic_cast<Cat*>(ani);//error
/*原因在於 dynamic_cast做類型安全檢查
子類指針可以轉換爲父類指針(從大到小),類型安全,因爲,子類包含父類的元素,指針作用域大,不會指針越界
父類指針轉換成子類指針(從小到達),類型不安全,會發生指針越界*/
Cat* cat = NULL;
Animal* ani2 = dynamic_cast<Animal*>(cat);
/*結論:
dynamic_cast只能轉換具有繼承關係的指針或者引用,並且
只能由子類型轉換爲基類型*/
}
//const_cast 指針 引用或者對象指針
void test03()
{
//1 基礎數據類型
int a = 10;
const int& b = a;
//b=10;//error 無法改變
int& c = const_cast<int&>(b);//const屬性取消
c = 20;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
cout << "c:" << c << endl;
/*輸出:
a:20
b:20
c:20
*/
//指針
const int* p = NULL;
int* p2 = const_cast<int*>(p);//OK
int* p3 = NULL;
const int* p4 = const_cast<const int*>(p3);//增加const屬性
/*結論:
增加或者去除變量的const屬性*/
}
//reinterpret_cast 強制類型轉換 無關的指針類型,包括函數指針都可以
typedef void(*FUNC1)(int, int);
typedef int(*FUNC2)(int, char*);
void test04()
{
//1. 無關的指針類型都可以進行轉換
Building* building = NULL;
Animal* ani = reinterpret_cast<Animal*>(building);
//2. 函數指針轉換
FUNC1 func1;
FUNC2 func2 = reinterpret_cast<FUNC2>(func1);
}
/*總結
結論1:程序員必須清楚的知道要轉變的變量,轉換前是什麼類型,轉換後是什麼類型,以及
轉換後有什麼結果
結論2:一般情況下,不建議類型轉換,避免進行類型轉換*/
int main()
{
cout<<"hello world"<<endl;
test01();
test03();
return 0;
}
總結
結論1:程序員必須清楚的知道要轉變的變量,轉換前是什麼類型,轉換後是什麼類型,以及
轉換後有什麼結果;
結論2:一般情況下,不建議類型轉換,避免進行類型轉換;