- Hands-On Embedded Programming with C++17
- Maya Posch
- 210字
- 2021-08-20 10:20:46
Type conversions
A type conversion occurs whenever a value is assigned to a compatible variable, which is not the exact same type as the value. Whenever a rule for conversion exists, this conversion can be done implicitly, otherwise an explicit hint (cast) can be provided to the compiler to invoke a specific rule where ambiguity exists.
Whereas C only has implicit and explicit type casting, C++ expands on this with a number of template-based functions, allowing you to cast both regular types and objects (classes) in a variety of ways:
- dynamic_cast <new_type> (expression)
- reinterpret_cast <new_type> (expression)
- static_cast <new_type> (expression)
- const_cast <new_type> (expression)
Here, dynamic_cast guarantees that the resulting object is valid, relying on runtime type information (RTTI) (see the later section on it) for this. A static_cast is similar, but does not validate the resulting object.
Next, reinterpret_cast can cast anything to anything, even unrelated classes. Whether this conversion makes sense is left to the developer, much like with a regular explicit conversion.
Finally, a const_cast is interesting in that it either sets or removes the const status of a value, which can be useful when you need a non-const version of a value for just one function. This does, however, also circumvent the type safety system and should be used very cautiously.
- Cortex-M3 + μC/OS-II嵌入式系統(tǒng)開發(fā)入門與應(yīng)用
- Android NDK Game Development Cookbook
- 數(shù)字邏輯(第3版)
- Mastering Manga Studio 5
- VCD、DVD原理與維修
- 微軟互聯(lián)網(wǎng)信息服務(wù)(IIS)最佳實(shí)踐 (微軟技術(shù)開發(fā)者叢書)
- 基于Apache Kylin構(gòu)建大數(shù)據(jù)分析平臺
- Spring Cloud微服務(wù)架構(gòu)實(shí)戰(zhàn)
- SiFive 經(jīng)典RISC-V FE310微控制器原理與實(shí)踐
- 超大流量分布式系統(tǒng)架構(gòu)解決方案:人人都是架構(gòu)師2.0
- STM32自學(xué)筆記
- Mastering Quantum Computing with IBM QX
- Building Machine Learning Systems with Python
- MicroPython Cookbook
- ActionScript Graphing Cookbook