简单理解>>此函数应用于 改变 const定义的 值
类型有int,char,string
代码如下:
#include<cstdio> #include<cstring> #include<string> #include<windows.h> using namespace std; int main() { int k = 0; const int i = k; const int I = k+1; /* 此处直接对const赋值无法改变i 因为编译器会进行优化,直接输出右边赋值量,而不会读取const后再输出 */ //两种定义方式 int *k = const_cast<int*>(&i); (*k)++; int &K = const_cast<int&>(I); K++; printf("i==%d I==%d ", i,I); const string a = "123"; const char A[]={"123"}; char* p = const_cast<char*>(a.c_str()); char* P = const_cast<char*>(A); strcpy(p, "abc"); strcpy(P, "def"); printf("a==%s A==%s ", a.c_str(),A); system("pause>nul"); return 0; } //主要学习于以下两位博客 //https://www.cnblogs.com/qiuchangyong/p/10028765.html //https://www.cnblogs.com/teng-IT/p/5981294.html