我的问题是关于"Effective C++"一书的特定项目(3).本书给出了这个例子,我尝试尽可能接近vs 2010 c ++(包括iostream和string):
class TextBlock {
public:
const char& operator[](std::size_t pos) const
{
return text[pos];
}
char& operator[](std::size_t pos)
{
return text[pos];
}
private:
std::string text;
};
void print(const TextBlock& ctb)
{
std::cout << ctb[0]; // OK
//ctb[0] = ‘A’; // Not OK – compiler error
}
int _tmain(int argc, _TCHAR* argv[])
{
TextBlock tb(“Hello”);
std::cout << tb[0];
tb[0] = ‘x’; // OK because return has &, not const
const TextBlock ctb("World");
std::cout << ctb[0];
return 0;
} …Run Code Online (Sandbox Code Playgroud)