c++中的const/const_cast

来源:互联网 发布:喜欢少年感的男生 知乎 编辑:程序博客网 时间:2024/05/22 17:18
  • const修饰普通变量
const double PI = 3.14159f;
  • 1
  • 1
  • const修饰指针变量
double const *pPi = Π
  • 1
  • 1
  • const修饰指针变量指向的变量
const double *pPi = Π
  • 1
  • 1
  • const修饰类成员属性
  • const修饰类成员函数,const成员函数内部不能调用非const修饰的成员函数,不过在不作修改的情况下可以调用非const的类成员属性
float PI = 2.14;float getPi(){    PI += 1;    return PI;}class CA{private:    const int a;    int b;public:    CA() :a(1), b(2) {}    int getA() const    {        // b++; // const函数不能修改非const类成员属性        int c = a+b; // const函数能调用非const类成员属性        getPi(); // const函数可以调用类外部非const函数        return a;    }    void  getCA() // const // const函数内部不能调用非const类成员函数    {        getA();        getB();    }    int getB()    {        // a++;        b += 2;        return b;    }};void test(){    CA ca;    cout << "ca.getA() : " << ca.getA() << endl;    cout << "ca.getB() : " << ca.getB() << endl;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • const_cast的使用: 
    本段代码摘自Working Draft, Standard for Programming 
    Language C++ N4582
int i = 2; // not cv-qualifiedconst int* cip; // pointer to const intcip = &i; // OK: cv-qualified access path to unqualified*cip = 4; // ill-formed: attempt to modify through ptr to constint* ip;ip = const_cast<int*>(cip); // cast needed to convert const int* to int**ip = 4; // defined: *ip points to i, a non-const objectconst int* ciq = new const int (3); // initialized as requiredint* iq = const_cast<int*>(ciq); // cast required*iq = 4; // undefined: modifies a const object
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

结构良好的代码应该不需要使用const_cast的。用错了不会报编译错误时,出现与编译器相关的未定义运行错误,非常危险。

原创粉丝点击