1.
#include <iostream> #include <string> using namespace std; class A { public: A(string x) { test = x; } const char& operator[](size_t pos) const {return test[pos];} char& operator[](size_t pos) {return test[++pos];} private: string test; }; int main() { A a("Hello"); cout << a[0]; const A b("Hello"); cout << b[0]; return 0; }
为什么const char& operator[](size_t pos) const 要返回一个const char &?