chapter_04
Tags
表达式
fundamentals
basic concept
Lvalues and Rvalues
evaluation,precedence and associativity
arithmetic operators
a = -i; 单元运算符的优先级很高,这里单元运算符返回了i 的相反数的复制出的值
并且,bool 类型的变量就不要参加运算了,特性是 “非零(正负)为真,零为假”
conversions
short + char = int: the result is int
sign + unsigned : if the sign value is more than the unsigned one, then the signed promoted to unsigned
array, pointer and reference
显示转换
dynamic_cast
这种强制转化支持运行时类型识别,我们将在第 19 章详细说
static_cast
- 支持的是不同类型的转换
- 不能对 low level 的const 进行转化
- 注意:由于 void* 可以接收任何类型,我们可以把其他指针类型的值存入 void* 的变量。而在重新将 void* 类型的值用 static_cast进行强转后,一定要转换为它原先的类型,否则可能会有 无定义 的错误发生。例:
const_cast
只用来 cast away const。在函数重载时可以用(后面接着介绍),其他时候也不建议。原因在于,使用了这个强制转换后,语法上获得了对原本 const 变量(可能是一个常量,也可能不是)的写权限。当要被转换的对象本身是一个常量,转后执行写操作会有未定义行为。只有当对象本身不是一个常量时,通过它获得写权限才是合法的。
reinterpret_cast
这个强制转换对转换的对象提供了较低层次的重新解释。就像同样的 unsigned char 和 char 同样的位数,解释方法不同了,意义就不同了。
用这个转换非常危险,你必须十分了解涉及的类型和编译器实现转换的过程。
关于旧式的强制转换
旧式的强制转换分别具有与 static_cast, const_cast, reinterpret_cast 相似的行为,具体执行哪种行为,可以用这种强制转换代替实验结果,如果不能用 static_cast 与 const_cast 代替旧式转换,则它执行与 reinterpret_cast类似的功能。
因此,当旧式强转处出现问题,更难追踪原因。
总之。不到万不得已,不要使用强制类型转换。
Loading...