const 成员函数:
将const实施于成员函数的目的,是为了确认该成员函数可作用于const对象身上。这一类成员函数之所以重要,第一,它们使class接口比较容易被理解。因为得知哪个函数可以改动对象内容哪个函数不行,是很重要的。第二,使“const对象”成为可能。
两个成员函数如果只是常量性(constness)不同,可以被重载。
class TextBlock{
const char& operator[] (std::size_t position) const
{ return text[position];} //const对象
char& operator[] (std::size_t position)
{ return text[position];} //non-const 对象
private:
std:string text;
}
TextBlock的operator[]s 可被这么使用:
TextBlock tb("Hello");
std::cout<<tb[0];
const TextBlock ctb("world");
std::cout<<cb[0];