标签:
const double PI = 3.14159f;
double const *pPi = Π
const double *pPi = Π
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;
}
int i = 2; // not cv-qualified
const int* cip; // pointer to const int
cip = &i; // OK: cv-qualified access path to unqualified
*cip = 4; // ill-formed: attempt to modify through ptr to const
int* ip;
ip = const_cast<int*>(cip); // cast needed to convert const int* to int*
*ip = 4; // defined: *ip points to i, a non-const object
const int* ciq = new const int (3); // initialized as required
int* iq = const_cast<int*>(ciq); // cast required
*iq = 4; // undefined: modifies a const object
结构良好的代码应该不需要使用const_cast的。用错了不会报编译错误时,出现与编译器相关的未定义运行错误,非常危险。
标签:
原文地址:http://blog.csdn.net/lonelyrains/article/details/51085192