可能重複:
When should static_cast, dynamic_cast and reinterpret_cast be used?C++鑄造運營商和傳統的C鑄造運營商
我已經做了google搜索找到有關的很多:
- 爲什麼要使用C++鑄造操作員比傳統的C風格鑄造操作員?
- 何時使用C++轉換操作符,一些活生生的實例?
以下是我發現:
- 傳統上的任何C++轉換操作符,用於更好的維護您的代碼(即),我們不難發現其中的鑄造通過在代碼只是在尋找這個曾經複雜的符號(reinterpret_cast <)不像C風格的鑄造操作符。
現在讓我簡要說明爲什麼當每個C++轉換操作符
的static_cast的:
爲什麼使用對C風格的鑄造? static_cast
用於相關類型之間的轉換。
例子:
Class A {};
Class B {};
A* a = new A();
B* b = static_cast<B*>(a); // Compiler error
B* b1 = (A*)a; // Works fine
float f;
int addr = (int)(&f); // Works fine
int addr = static_cast<int>(&f); // Compiler error
但我想知道何時使用上面的代碼真正的用例?
的reinterpret_cast:
reinterpret_cast
蒙上指向不相關的類型。
例子:
Class A {};
Class B {};
A* a = new A();
B* b = reinterpret_cast<B*>(a); // Works fine
B* b1 = (A*)a; // Works fine
float f;
int addr = (int)(&f); // Works fine
int addr = reinterpret_cast<int>(&f); // Works fine
int ai = 10;
float af = 13.33;
// Would depend on how floating point is stored in machine
// int& since reinterpret_cast expects either the type or operand to be pointer or reference
int ki = reinterpret_cast<int&>(af); // ki would not be 13
int kitemp = (int)af; // kitemp would be 13
// The same reinterpret_cast behaviour can be achieved using this,
int* in = (int*)(af);
cout << (*in);
我的問題是怎麼回事,是由C風格的鑄造reinterpret_cast
不同?我無法找到與傳統鑄造操作員一起使用它的原因,以及何時使用它?
這使得這些運營商更糟另一個重要的例子是:
const unsigned int * p;
(int*)p; // Would remove unsigned and const at one shot
// Using C++ casting operators
// Const_cast expects a pointer or a reference
reinterpret_cast<int*>(const_cast<unsigned int* >(p));
編寫上述代碼除去const
和unsigned
要複雜得多在C++鑄造?那麼,爲什麼人們使用reinterpret_cast
,const_cast
或static_cast
在土產Ç鑄造運營商?
我明白約dynamic_cast
在多態類的情況下使用;這個運營商也有額外的RTTI費用。
C++轉換是C風格演員的限制版本,它試圖幾乎每一個演員,直到它找到一個作品。當您想要進行某種類型的轉換時,應該使用C++樣式類型轉換,並且如果無法執行該類型的轉換,則編譯將失敗,其中C類型轉換用於「只做」轉換。 – 2011-12-26 06:20:35
@Mat:從你建議的鏈接中,我瞭解了很多。但我在下面有一個疑問,你如何將這種類型的例子映射到C風格的鑄造,float a = 13.33; int b = reinterpret_cast(a); ...請讓我明白這個 –
2011-12-26 07:28:52
@RishiMehta:我不知道該演員應該扮演什麼角色_mean_。你爲什麼要寫這樣的「東西」? – Mat 2011-12-26 08:43:56