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的值
(1)我们可能调用了一个参数不是const的函数,而我们要传进去的实际参数确实const的,但是我们知道这个函数是不会对参数做修改的。于是我们就需要使用const_cast去除const限定,以便函数能够接受这个实际参数。
(2)定义了一个非const的变量,但用带const限定的指针去指向它,在某一处我们突然又想修改了,可是我们手上只有指针,这时候我们可以去const来修改了。
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来修改了。
相关文章推荐
- C++标准转换运算符const_cast
- C++标准转换运算符const_cast
- C++标准转换运算符const_cast
- C++类型转换运算符: static_cast<>,reinterpret_cast<>,dynamic_cast<>, const_cast<>
- 关于c++ 强制转换类型运算符 static_cast、dynamic_cast、reinterpret_和const_cast
- 标准c++中四种强制转换类型运算符介绍 const_cast,reinterpret_cast,static_cast,dynamic_cast
- C++标准转换运算符const_cast
- C++_转换运算符_const_cast
- C++标准转换运算符const_cast
- c++中的四个转换运算符(,static_cast,const_cast,dynamic_cast,reinterpret_cast)
- C++标准转换运算符const_cast
- C++标准转换运算符const_cast
- C++标准转换运算符const_cast
- C++标准转换运算符const_cast - Ider - 博客园
- C++标准转换运算符const_cast
- C++标准转换运算符const_cast
- C++标准转换运算符const_cast
- C++标准转换运算符const_cast
- C++的类型转换运算符(二)——reinterpret_cast 与 const_cast
- 【C++基础】类型转换运算符的使用方法(reinterpret_cast、 const_cast、static_cast、dynamic_cast)