effective c++中const的理解

方紫涵 方紫涵 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
const char& operator[] (std::size_t position) const //问下前面的那个const有什么用阿 ?去掉的话会error: invalid initialization of reference of type ‘char&’ from expression of type ‘const char’ ,这个error里面const char是怎么来的 ?

   
class TextBlock {
public:
...
const char& operator[] (std::size_t position) const
{return text[position];}
char& operator[] (std::size_t position)
{return text[position];}
private:
std::string text;
}

TextBlock tb("Hello");
std::cout << tb[0];

const TextBlock ctb("World");
std::cout << ctb[0];
...全文
评论 25
收藏 已收藏
分享
返回顶部
方紫涵
C++ 语言 65,213 成员 250,513 内容