您的位置:首页 > 编程语言 > C语言/C++

C++转换运算符之const_cast

2016-08-05 11:13 267 查看
C++提供了四个转换运算符:

const_cast <new_type> (expression)

static_cast <new_type> (expression)

reinterpret_cast <new_type> (expression)

dynamic_cast <new_type> (expression)
 c 语言中怎么去除 const 修饰? 比如:const int value=0.2f; int *ptr;ptr
怎么样获取 value 的值?

答:const* int const_p=&value;

       int* ptr=const_cast(const_p);

两种错误的方式:(1)  int modify=&value;(2) int*
modify=&value;

传统方式可写成: int* modify=(int*) &value; 

 这部分详细解释可参考http://www.cnblogs.com/ider/archive/2011/07/22/cpp_cast_operator_part2.html

这样修改完成后value还是保留了它原来的值,可是它们指向了同一个地址.此时我们不能修改value的值可是能修改modify的值


为何要去除const限定

(1)我们可能调用了一个参数不是const的函数,而我们要传进去的实际参数确实const的,但是我们知道这个函数是不会对参数做修改的。于是我们就需要使用const_cast去除const限定,以便函数能够接受这个实际参数。

(2)定义了一个非const的变量,但用带const限定的指针去指向它,在某一处我们突然又想修改了,可是我们手上只有指针,这时候我们可以去const来修改了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: