参考effective c++
1. 与指针配合
char * str="Hello";
const char * p = str;//指向常量的指针
p[0]='h'; //wrong
p="Hi"; //Ok
char const * pp=str;//同上 只关心const相对于 * 位置
char * const cp=str;//指针常量 不允许指向其他的地址
cp[0]='h'; //Ok 此处运行有错误 "Hello"编译时 常量 赋值出错
cp="Hi"; //wrong
const char * const pp=str;
2. 修饰函数参数或返回值
class Widget;
const Widget operator=(const Widget& lhs,const Widget& rhs);//防止 if((a*b)=c)这样的暴行
//= *= += -=等符合运算符都需要返回const
3. 类中修饰函数 const函数
//提供const函数的原因
//1. 供const对象调用
//2. 使接口更容易被理解 接口是否可以改变对象
class MyString
{
private:
char* str;
const char& operator[](unsigned int i) const
{
return str[i];
}
char& operator[](unsigned int i)
{
return const_cast<char&>(static_cast<const Mystring&>(*this)[i]);//避免代码重复
}
}