const的使用情况

#pragma once
#include<string>
 
class TextBlock {

public:
	//const 的意义 const 基本意思就是不让修改  
	//1.返回值加const 意味着它不能成为左值(左值可修改)
	//2.函数后加const 不能修改类中的数据,const对象可调用后加const的函数,const函数只能调用const函数 

	//另外两种情况 
	//1.char const *pvalue		*pvalue 取得的内容不让改变
	//2.char* const pvalue		pvalue指向的内容不变
	TextBlock(const std::string sz):text(sz) {}
	const char& operator[](std::size_t position)const
	{
		return text[position];
	}
	//char& operator[](std::size_t position) { return text[position]; }
	char& operator[](std::size_t position) {
		return const_cast<char&>(					//取消const
			static_cast<const TextBlock&>(*this)	//转成const 对象然后调用const 的operator[]
			[position]
			);
	}
	//利用non-const 成员函数调用const 函数是可接受的,如果其有相同的实现,可以避免代码重复

	void Usemutable(int nLen)const		//这里通过const 函数对mutable 修饰的属性进行修改
	{
		textLength = nLen;
	}
private:
	std::string text;
	mutable std::size_t textLength;

	//keyword mutable 表示即使在const函数内部也可以被修改


};

内容来源于effective C++

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值