函数传参
void f(const int& x) //x在函数中不可修改,且传入时直接传入x本身
成员函数中
struct Planet{
int countPopulation() const;
void deathStar();
};
void evil(const Planet &p){
//countPopulation函数是获取对象状态的成员函数
cout << p.countPopulation() << endl;
//错误:deathStar是修改对象状态的成员函数
p.deathStar();
}
常成员函数不能修改对象成员的值
指针中
int * const p; //p为指向固定地址的整型指针
(*p)++; //OK
p++; //Not allowed
const int* p;
int const* p; //p均为指向整型常量的指针
const int * const p;
int const * const p; //p均为指向固定地址的整型常量的指针
迭代器中
const vector<int>::iterator itr = v.begin(); //与 int* const itr 相似
++itr; //doesn't compile
*itr = 15; //compiles
vector<int>::const_iterator itr = v.begin();
*iter = 5; //不能修改itr所指的值
++itr; //OK
int value = *itr; //OK
参考文献:
1.CS106L
2.https://blog.youkuaiyun.com/haitaolang/article/details/70162903?fromshare=blogdetail&sharetype=blogdetail&sharerId=70162903&sharerefer=PC&sharesource=znhai&sharefrom=from_link