【发布时间】:2015-07-17 20:33:20
【问题描述】:
我正在学习 C++,但无法理解一些概念。在下面的程序中,(1)为什么用char&而不是char,我觉得应该只用一个char,因为成员函数返回text[position]而这是char类型,不是一个参考。 (2) 在const char& operator[](std::size_t position) const 中,为什么需要第二个const?我试图删除它并只保留第一个const,但它报告了错误。谢谢你。
#include<iostream>
#include<string>
class TextBook{
public:
TextBook(std::string s)
{
text.assign(s);
}
const char& operator[](std::size_t position) const {
return text[position];
}
char& operator[](std::size_t position){
return text[position];
}
private:
std::string text;
};
int main()
{
const TextBook ctb("Hello");
std::cout << ctb[0] << std::endl;
TextBook tb("Morning");
tb[2]='M';
std::cout << tb[2] << std::endl;
}
【问题讨论】:
-
test[position]是对char的引用(或const char,取决于你的意思)。