C++ const用法实例

函数传参

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值