1 #include<iostream>
2 #include<string>
3 using namespace std;
4
5 class TextBlock{
6 public:
7 TextBlock(string x):text(x){
8 }
9 //operator[] for const 对象
10 const char& operator[](std::size_t position) const
11 { return text[position]; }
12
13 //operator[] for non-const 对象
14 char operator[](std::size_t position)
15 { return text[position]; }
16
17 private:
18 std::string text;
19 };
20
21 int main(){
22 TextBlock tb("hello");
23 tb[0] = 'x'; //报错: lvalue required as left operand of assignment
24
25 std::cout << tb[0] << endl;
26
27
28 const TextBlock ctb("World!!");
29 std::cout << ctb[0];
30
31 }
