#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++