we have four specific casting operators:dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.
dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)
一、对C++中四种类型转换总结如下:
const_cast<T>(expr)
用来移除对象的常量性(cast away the constness)
const_cast一般用于指针或者引用
使用const_cast去除const限定的目的不是为了修改它的内容
使用const_cast去除const限定,通常是为了函数能够接受这个实际参数
static_cast<T>(expr)
编译器隐式执行的任何类型转换都可以由static_cast完成
当一个较大的算术类型赋值给较小的类型时,可以用static_cast进行强制转换。
可以将void*指针转换为某一类型的指针
可以将基类指针强制转换为派生类指针,但是不安全。
无法将const转化为nonconst,这个只有const_cast才可以办得到
reinterpret_cast<T>(expr)
“通常为操作数的位模式提供较低层的重新解释”也就是说将数据以二进制存在形式的重新解释。
int i;
char *p = "This is a example.";
i = reinterpret_cast<int>(p);
//此时结果,i与p的值是完全相同的。
int *ip
char *pc = reinterpret_cast<char*>(ip);
// 程序员需要记得pc所指向的真实对象是int型,并非字符串。
// 如果将pc当作字符指针进行操作,可能会造成运行时错误
// 如int len = strlen(pc);
多重继承时reinterpret_cast不安全。static_cast会根据父子类指针转换的偏移量转换到正确地址,而reinterpret_cast不会。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <cassert>
|