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
{
int c = a+b;
getPi();
return a;
}
void getCA()
{
getA();
getB();
}
int getB()
{
b +=
2;
return b;
}
};
void test()
{
CA ca;
cout <<
"ca.getA() : " << ca.getA() << endl;
cout <<
"ca.getB() : " << ca.getB() << endl;
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
const_cast的使用: 本段代码摘自Working Draft, Standard for Programming Language C++ N4582
int i =
2;
const int* cip;
cip = &i;
*cip =
4;
int* ip;
ip =
const_cast<
int*>(cip);
*ip =
4;
const int* ciq =
new const int (
3);
int* iq =
const_cast<
int*>(ciq);
*iq =
4;
12345678910
12345678910
结构良好的代码应该不需要使用const_cast的。用错了不会报编译错误时,出现与编译器相关的未定义运行错误,非常危险。