zoukankan      html  css  js  c++  java
  • const_cast

    简单理解>>此函数应用于    改变   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
  • 相关阅读:
    CF-807B
    CF-807A
    sort()的升降序函数操作
    CF-805D
    CF-805B
    CF-805A
    CF-796C
    CF-796B
    图论学习四之Disjoint set union并查集
    图论学习三之Shortest Path最短路
  • 原文地址:https://www.cnblogs.com/Renhr/p/13420138.html
Copyright © 2011-2022 走看看