新聞中心
本篇內(nèi)容介紹了“C++怎么使用命名轉(zhuǎn)換”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
為延津等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及延津網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站制作、成都做網(wǎng)站、延津網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
ES.49:如果必須進(jìn)行類型轉(zhuǎn)換,使用命名轉(zhuǎn)換
Reason(原因)
可讀性。避免錯誤。命名轉(zhuǎn)換比C風(fēng)格轉(zhuǎn)換或函數(shù)形式轉(zhuǎn)換更明確,允許編譯器捕捉更多錯誤。
The named casts are:
命名轉(zhuǎn)換包括:
static_cast
靜態(tài)轉(zhuǎn)換
const_cast
常量轉(zhuǎn)換
reinterpret_cast
重新解釋轉(zhuǎn)換
dynamic_cast
動態(tài)轉(zhuǎn)換
std::move // move(x) is an rvalue reference to x
移動//move(x)是x的右值引用
std::forward // forward
(x) is an rvalue or an lvalue reference to x depending on T 值性轉(zhuǎn)遞//根據(jù)T的類型,forward
(x)是左值或右值引用 gsl::narrow_cast // narrow_cast
(x) is static_cast (x) 窄化轉(zhuǎn)換//narrow_cast
(x)就是static_cast (x) gsl::narrow // narrow
(x) is static_cast (x) if static_cast (x) == x or it throws narrowing_error 窄化轉(zhuǎn)換(拋出異常)//如果static_cast
(x) == x,narrow (x) 就是 static_cast (x),否則拋出異常
Example(示例)
class B { /* ... */ };
class D { /* ... */ };
template D* upcast(B* pb)
{
D* pd0 = pb; // error: no implicit conversion from B* to D*
D* pd1 = (D*)pb; // legal, but what is done?
D* pd2 = static_cast(pb); // error: D is not derived from B
D* pd3 = reinterpret_cast(pb); // OK: on your head be it!
D* pd4 = dynamic_cast(pb); // OK: return nullptr
// ...
}
示例是從實際代碼中收集的的錯誤集合,這段代碼的前提是D過去繼承于B,但有人重構(gòu)了繼承關(guān)系。C風(fēng)格轉(zhuǎn)換的危險性來自它可以是任何類型的轉(zhuǎn)換,這抹殺了任何防錯保護(hù)的可能性(無論是現(xiàn)在還是未來)。
Note(注意)
如果希望在類型之間進(jìn)行無損轉(zhuǎn)換(例如從float到double,或者從int32到int64),可以考慮轉(zhuǎn)而使用大括號初始化。
double d {some_float};
int64_t i {some_int32};
這種方式一方面明確了類型轉(zhuǎn)換的意圖,另一方面可以防止轉(zhuǎn)換時損失精度。(例如,在如代碼所示的情況下,如果使用double值初始化float變量,會發(fā)生編譯錯誤)
Note(注意)
reinterpret_cast can be essential, but the essential uses (e.g., turning a machine address into pointer) are not type safe:
reinterpret_cast是必不可少的,但是這種必要的用法(例如,將機器地址轉(zhuǎn)換為指針)不是類型安全的。
auto p = reinterpret_cast(0x800); // inherently dangerous
Enforcement(實施建議)
Flag C-style and functional casts.
對C風(fēng)格和函數(shù)形式轉(zhuǎn)換進(jìn)行提醒
The type profile bans reinterpret_cast.
類型規(guī)則群組禁止reinterpret_cast.
The type profile warns when using static_cast between arithmetic types.
類型規(guī)則群組對在算數(shù)類型之間進(jìn)行轉(zhuǎn)換時使用static_cast的情況進(jìn)行警告。
譯者注:
C風(fēng)格轉(zhuǎn)換:b = int(a);
函數(shù)形式轉(zhuǎn)換:b=int(a);
“C++怎么使用命名轉(zhuǎn)換”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
當(dāng)前文章:C++怎么使用命名轉(zhuǎn)換
新聞來源:http://fisionsoft.com.cn/article/piepei.html