const_cast 用法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了const_cast 用法相关的知识,希望对你有一定的参考价值。
const_cast 用法
语法:
const_cast<type-name>(expression);
作用:
1. 将const对象的地址赋给同类型的非const指针。例如:
const int val = 100;
int * pv = const_cast<int *>(&val);
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); } }
测试结果:
[email protected]:~/project/CppPrimerPlus/Chapter 15$ ./a.out
val_1 = 112
val_2 = 34
val_3 = 56
val_4 = 78
val_5 = 78
本文出自 “用C++写诗” 博客,谢绝转载!
以上是关于const_cast 用法的主要内容,如果未能解决你的问题,请参考以下文章