标签:c++
const_cast 用法
语法:
const_cast<type-name>(expression);
作用:
1. 将const对象的地址赋给同类型的非const指针。例如:
const int val = 100;
int * pv = const_cast<int *>(&val);
但是,仍然无法通过这个非const指针pv来修改const对象val。所以,我觉得 const_cast 没有什么用。
2. 将非const对象的地址赋给同类型的const指针。例如:
int val = 100;
const int * pc = const_cast<const int *>(&val);
3. type-name 和 expression 的类型必须相同。
#include<cstdio> int main() { // assign address of "int object" to "int *" pointer. { int val_1 = 12; int *ptr_1 = const_cast<int *>(&val_1); *ptr_1 += 100; printf("val_1 = %d\n", val_1); } // assign address of "const int object" to "int *" pointer. { const int val_2 = 34; int *ptr_2 = const_cast<int *>(&val_2); *ptr_2 += 100; printf("val_2 = %d\n", val_2); } // assign address of "int object" to "const int *" pointer. { int val_3 = 56; const int *ptr_3 = const_cast<const int *>(&val_3); //*ptr_3 += 100; //error: assignment of read-only location ‘* ptr_3’ printf("val_3 = %d\n", val_3); } // assign address of "const int object" to "const int *" pointer. { const int val_4 = 78; const int *ptr_4 = const_cast<const int *>(&val_4); //*ptr_4 += 100; error: assignment of read-only location ‘* ptr_4’ printf("val_4 = %d\n", val_4); } // assign address of "const int object" to "char *" pointer. { const int val_5 = 78; //char *ptr_5 = const_cast<char *>(&val_5); error: invalid const_cast from type ‘const int*’ to type ‘char*’ //*ptr_5 += 100; error: assignment of read-only location ‘* ptr_5’ printf("val_5 = %d\n", val_5); } }
测试结果:
frank@userver:~/project/CppPrimerPlus/Chapter 15$ ./a.out
val_1 = 112
val_2 = 34
val_3 = 56
val_4 = 78
val_5 = 78
本文出自 “用C++写诗” 博客,谢绝转载!
标签:c++
原文地址:http://frankniefaquan.blog.51cto.com/12613979/1939622