首页 / 软件开发 / C++ / C++中四种类型转换 const_cast是否能改变常量
C++中四种类型转换 const_cast是否能改变常量2013-11-04we have four specific castingoperators: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(expr)用来移除对象的常量性(cast away the constness)const_cast一般用于指针或者引用使用const_cast去除const限定的目的不是为了修改它的内容使用const_cast去除const限定,通常是为了函数能够接受这个实际参数static_cast(expr)编译器隐式执行的任何类型转换都可以由static_cast完成当一个较大的算术类型赋值给较小的类型时,可以用static_cast进行强制转换。可以将void*指针转换为某一类型的指针可以将基类指针转换为派生类指针无法将const转化为nonconst,这个只有const_cast才可以办得到reinterpret_cast(expr)“通常为操作数的位模式提供较低层的重新解释”也就是说将数据以二进制存在形式的重新解释。int i;char *p = "This is a example.";i = reinterpret_cast<int>(p);//此时结果,i与p的值是完全相同的。int *ipchar *pc = reinterpret_cast<char*>(ip);// 程序员需要记得pc所指向的真实对象是int型,并非字符串。// 如果将pc当作字符指针进行操作,可能会造成运行时错误// 如int len = strlen(pc);dynamic_cast(expr)执行“安全向下”转型操作,也就是说支持运行时识别指针或所指向的对象,这是唯一个无法用旧式语来进行的转型操作。dynamic_cast可谓是最严格的转换,static_cast次之,而reinterpret_cast则是最宽松的。如果你遇到不能将整型转变为函数指针的问题,你可以这样解决:reinterpret_cast<LPFUN&>(nAddress);注意LPFUN这里有个“&”符号,表示引用,C++的引用其实就是用指针实现的,而这些“转换”其实都是指针的转换,所以加上引用符号编译才能通过。