當前位置:才華齋>計算機>C語言>

C++的型別轉換介紹

C語言 閱讀(2.76W)

C語言一共只有32個關鍵字,9種控制語句,程式書寫形式自由,區分大小寫。下面是小編分享的C++的型別轉換介紹,一起來看一下吧。

C++的型別轉換介紹

  1、型別轉換名稱和語法

C風格的強制型別轉換(Type Cast)很簡單,不管什麼型別的轉換統統是:

TYPE b = (TYPE)a

C++風格的型別轉換提供了4種類型轉換操作符來應對不同場合的應用。

static_cast 靜態型別轉換。如int轉換成char

reinterpreter_cast 重新解釋型別

dynamic_cast 命 名上理解是動態型別轉換。如子類和父類之間的多型型別轉換。

const_cast 字面上理解就是去const屬性。

4種類型轉換的格式

TYPE B = static_cast<TYPE> (a)

  2、型別轉換一般性介紹

4中型別轉化介紹

1)static_cast<>() 靜態型別轉換,編譯的時c++編譯器會做型別檢查;

基本型別能轉換 但是不能轉換指標型別

2)若不同型別之間,進行強制型別轉換,用reinterpret_cast<>() 進行重新解釋

3)dynamic_cast<>(),動態型別轉換,安全的基類和子類之間轉換;執行時型別檢查 (C++特有的)

4)const_cast<>(),去除變數的只讀屬性(C++特有的'),變數的型別必須是指標,指標指向的記憶體空間可被修改

一般性結論

C語言中 能隱式型別轉換的,在c++中可用 static_cast<>()進行型別轉換。因C++編譯器在編譯檢查一般都能通過;

C語言中不能隱式型別轉換的,在c++中可以用 reinterpret_cast<>() 進行強行型別 解釋。

static_cast<>()和reinterpret_cast<>() 基本上把C語言中的 強制型別轉換給覆蓋

reinterpret_cast<>()很難保證移植性。

  3、典型案例

程式碼中包含了4中型別轉化的例項,以及注意點。

#include<iostream>

using namespace std;

class Animal

{

public:

virtual void action()

{

cout<<"the action is animal's "<<endl;

}

};

class Dog:public Animal

{

public:

virtual void action()

{

cout<<"the action is dog's "<<endl;

}

void doSwim()

{

cout<<"the dog is swimming..."<<endl;

}

};

class Cat:public Animal

{

public:

virtual void action()

{

cout<<"the action is cat's "<<endl;

}

void doTree()

{

cout<<"the cat is claming tree..."<<endl;

}

};

class Desk

{

public:

void action()

{

cout<<"this is Desk, not belong Animal"<<endl;

}

};

void ObjPlay(Animal *animl)

{

animl->action();

Dog *dog = dynamic_cast<Dog *>(animl);

if(dog!=NULL) //判斷是不是dog

{

dog->action();

dog->doSwim();

}

Cat *cat = dynamic_cast<Cat *>(animl);

if(cat!=NULL) //判斷是不是cat

{

cat->action();

cat->doTree();

}

cout<<"func ObjPlay is exit!!!"<<endl;

}

//典型用法 把形參的只讀屬性去掉

void Opbuf(const char *p)

{

cout << p << endl;

//char *p2 = p; err:const char *不能初始化為char *

//p[0] = 'b'; err:必須是可修改的左值

char *p2 = const_cast<char*>(p); //去除只讀的屬相

p2[0] = 'b';

cout << p << endl;

}

int main()

{

//靜態型別轉化 static_cast<>()

double d = 3.14159;

int i1,i2;

i1 = d; //C中的隱式型別轉化

i2 = static_cast<int>(d); //C++中的靜態型別轉化

cout<<"C中型別轉化:"<<i1<<endl;

cout<<"C++中型別轉化:"<<i2<<endl;

//重新解釋型別reinterpret_cast<>()

char *p = "abcd";

int *p1 = NULL;

int *p2 = NULL;

p1 = (int *)p; //C中強制型別轉化

//p2 = static_cast<int *>(p); 編譯報錯,型別轉化錯誤,靜態型別不能轉化指標

p2 = reinterpret_cast<int *>(p); //C++中的重新解釋型別

cout<<"C中型別轉化"<<hex<<*p1<<endl;

cout<<"C++中型別轉化:"<<hex<<*p2<<endl;

//動態型別轉換 dynamic_cast<>()

Animal an;

Animal *pAn = &an;

ObjPlay(pAn);

Dog dog;

Dog *pDog = &dog;

ObjPlay(pDog);

Cat cat;

Cat *pCat = &cat;

ObjPlay(pCat);

Desk desk;

Desk *pDesk = &desk;

//Animal *pAn = dynamic_cast<Animal*>(pDesk); 不同的基類指標之間不能相互轉化,安全

//去除變數的只讀屬性,const_cast<>(),此型別必須是指標

char buf[100] = "aaaaaaaaaaaa";

//Opbuf(buf);

//要保證指標所執行的記憶體空間能修改才行 若不能修改 還是會引起程式異常

//Opbuf("dddddddddddsssssssssssssss");

system("pause");

return 0;

}