Regular cast vs. static_cast vs.dymamic_cast in C++

來源:互聯網
上載者:User

標籤:style   使用   os   io   art   ar   amp   c++   

介紹C++類型轉換的用法。

1.static_cast

static_cast用與強制隱式類型轉換,即隱式類型轉換的反方向。static_cast,限制條件少,不進行運行時檢驗。

必須用於當你知道對象的具體類型時,這樣檢驗是不必要的,否則,不安全。

example:

 

void func(void *data) {  // Conversion from MyClass* -> void* is implicit  MyClass *c = static_cast<MyClass*>(data);  ...}int main() {  MyClass c;  start_thread(&func, &c)  // func(&c) will be called      .join();}


在這個例子中,你已經知道傳入的是一個MyClass 對象,沒有必要進行運行時檢驗。

 

如果將一個非MyClass 對象傳入func中,會如何呢,看下面code,

 

#include<iostream>using namespace std;class A{public:A(){i=0;j=12;}int i;int j;};void cast_f(void *ptr){A * p=static_cast<A *>(ptr);cout<<p->i<<endl;cout<<p->j<<endl;} int main(){int a=11;int * p=&a;cast_f(p);cin.get();return 0;}

輸出11和一個未知數。而不是0和12。 這就要我們確保已知傳入的物件類型。否則,不安全。

 

2.dynamic_cast

dynamic_cast用在當你不知道對象的動態類型是什麼的時候,而你想在一個你認定為繼承類對象身上執行繼承類的操作函數,但你的手上卻只有一個指向基類對象的指標或者引用。若為downcast並且型別參數不為多態時,不能使用dynamic_cast,編譯器報錯。

dynamic_cast 返回一個null指標,如果對象的類型不是以將要轉換為的類型為基類的話。即,非衍生類別對象轉為基類對象,或者基類對象轉為衍生類別對象,均返回null指標。

 

 

#include<iostream>using namespace std;class A{public:virtual void f(){cout<<"A"<<endl;}};class B:public A{public:void dynamic_f(){cout<<"called dynamic_f()"<<endl;} };int main(){A a;B *b=dynamic_cast<B *>(&a);//when downcast, if a is not object of class B,return null pointer.if(!b){cout<<"null"<<endl;}else{cout<<"not null"<<endl;}A *aa=0;//基類指標 B bb;aa=&bb;//指向衍生類別//aa如何調用dynamic_f()呢? aa.dynamic_f()當然不行了,編譯不通過B *ba=dynamic_cast<B*>(aa);ba->dynamic_f();cin.get();return 0;}



 

這個例子中,將基類對象轉換為衍生類別對象,返回一個null指標。

 

up-cast(向上轉換)是隱式轉換,對static_cast,dynamic_cast,without any cast均有效。

3.Regular cast

Regular cast 又稱為C風格類型轉換。C-style cast,結合const_cast,static_cast,reinterpret_cast,但是它是不安全的,因為不支援dynamic_cast。

通常在數字轉換時用C-style cast,其他用c++風格的cast。另外,c++風格的更易讀。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.