为避免重复代码,operator[]左值操作符可以用其右值操作符来构造
class BookTest
{
public:
BookTest(const string& name);
virtual ~BookTest();
const char& operator[](size_t index)const
{
cout<<"const"<<endl;
return bookname[index];
}
char& operator[](size_t index)
{
cout<<"inconst"<<endl;
return const_cast<char&>(static_cast<const BookTest&>(*this)[index]);
}
const string &getBookName()
{
return bookname;
}
private:
string bookname;
};
int main()
{
BookTest("hello");
Test[0] = 'J';
}
//运行结果 inconst
const