C++標準轉換運算子static_cast

來源:互聯網
上載者:User
static_cast <new_type> (expression)

雖然const_cast是用來去除變數的const限定,但是static_cast卻不是用來去除變數的static引用。其實這是很容易理解的,static決定的是一個變數的範圍和生命週期,比如:在一個檔案中將變數定義為static,則說明這個變數只能在本Package中使用;在方法中定義一個static變數,該變數在程式開始存在直到程式結束;類中定義一個static成員,該成員隨類的第一個對象出現時出現,並且可以被該類的所有對象所使用。

對static限定的改變必然會造成範圍性的影響,而const限定的只是變數或對象自身。但無論是哪一個限定,它們都是在變數一出生(完成編譯的時候)就決定了變數的特性,所以實際上都是不容許改變的。這點在const_cast那部分就已經有體現出來。

static_cast和reinterpret_cast一樣,在面對const的時候都無能為力:兩者都不能去除const限定。兩者也存在的很多的不同,比如static_cast不僅可以用在指標和引用上,還可以用在基礎資料和對象上;前面提到過reinterpret_cast可以用在"沒有關係"的類型之間,而用static_cast來處理的轉換就需要兩者具有"一定的關係"了。

還是用例子來說明比較直觀一些。

還是用例子來說明比較直觀一些。

在reinterpret_cast一篇,已經提到過reinterpret_cast可以在任意指標之間進行互相轉換,即使這些指標所指的內容是毫無關係的,也就是說一下語句,編譯器是不會報錯的,但是對於程式來說也是毫無意義可言的,只會造成程式崩潰:

#include <iostream>using namespace std;unsigned short Hash( void *p ) {unsigned long val = reinterpret_cast<unsigned long>( p );return ( unsigned short )( val ^ (val >> 16));}class Something{/* Some codes here */};class Otherthing{/* Some codes here */};int main() {typedef unsigned short (*FuncPointer)( void *) ;FuncPointer fp = Hash;//right, this is what we wantint a[10];const int* ch = a; //right, array is just like pointerchar chArray[4] = {'a','b','c','d'};fp = reinterpret_cast<FuncPointer> (ch); //no error, but does not make sensech = reinterpret_cast<int*> (chArray);//no errorcout <<hex<< *ch;//output: 64636261//it really reinterpret the pointerSomething * st = new Something();Otherthing * ot = reinterpret_cast<Otherthing*> (st); //cast between objects with on relationship}

而以上轉換,都是static_cast所不能完成的任務,也就是說把上邊程式裡所有的reinterpret_cast換成static_cast的話,就會立即得到編譯錯誤,因為目標指標和原始指標之間不存在"關係"

從上邊的程式,也就一下子看出來了reinterpret_cast和static_cast之間最本質的區別。

而以上轉換,都是static_cast所不能完成的任務,也就是說把上邊程式裡所有的reinterpret_cast換成static_cast的話,就會立即得到編譯錯誤,因為目標指標和原始指標之間不存在"關係"

從上邊的程式,也就一下子看出來了reinterpret_cast和static_cast之間最本質的區別。

對於static_cast所需要的關係,"繼承"絕對是其中之一,所以static_cast支援指向基類的指標和指向子類的指標之間的互相轉換:

class Parents{public:virtual ~Parents(){}/*codes here*/};class Children : public Parents{/*codes here*/};int main() {Children * daughter = new Children();Parents * mother = static_cast<Parents*> (daughter); //right, cast with polymorphismParents * father = new Parents();Children * son = static_cast<Children*> (father); //no error, but not safe}

但是從基類到子類的轉換,用static_cast並不是安全的,具體的問題會在dynamic_cast一篇闡述。

在指標和引用方便,似乎也只有繼承關係是可以被static_cast接受的,其他情況的指標和引用轉換都會被static_cast直接扔出編譯錯誤,而這層關係上的轉換又幾乎都可以被dynamic_cast所代替。這樣看起來static_cast運算子的作用就太小了。

實際上static_cast真正用處並不在指標和引用上,而在基礎類型和對象的轉換上 。 而基於基礎類型和對象的轉換都是其他三個轉換運算子所辦不到的。

這些轉換跟C++使用者自訂類型轉換一文中所設計的內容比較接近,所以在那邊文章中出現轉換可以全部加上static_cast。

基礎類型轉換:

float floatValue = 21.7;
int intValue = 7;

cout << floatValue / 7 << "\t\t" << static_cast<int> (floatValue)/7 <<endl;
cout << intValue/3 << "\t\t" << static_cast<double> (intValue)/3 << endl;

//Output:
//3.1     3
//2       2.33333

從輸出結果可以看出轉換是成功並且正確的。

對於對象的轉換,也是需要又關係的,這層關係就是C++使用者自訂類型轉換中提到的方法:

  • 建構函式(Constructor)
  • 類型轉換運算子(Type –Cast Operator

static_cast會根據上述順序尋找到合適的方法進行類型轉換。

賦值運算子並不被算在內,因為它自身已經是一種運算子,不能再當做轉換運算子來用。

int main(void) {Ape a; Human h = static_cast<Human> (a); // using promtion constructorProgrammer p;p = static_cast<Programmer> (h); // using  Programmer-cast operaotor//Ape a2;//a2 = static_cast<Ape> (p); //Error, assignment operator should be used directlyreturn 0;}

(類的代碼見C++使用者自訂類型轉換,或者下載代碼查看)

傳統轉換方式實現static_cast運算子

從上邊對static_cast分析可以跟看,static_cast跟傳統轉換方式幾乎是一致的,所以只要將static_cast和圓括弧去掉,再將角括弧改成圓括弧就變成了傳統的顯示轉換方式。在C++使用者自訂類型轉換一文已有很多的介紹了。

Director: Jim Fawcett
  1. C++ Language Tutorial - Type Casting
  2. Object Oriented Design
  3. IBM Complilers - XL C/C++ V9.0 for Linux - The static_cast operator (C++ only)
  4. Bjarne Stroustrup's C++ Style and Technique FAQ - What good is static_cast?
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.