1. 设计准则
- 必须定义为成员函数。
- 通常返回访问元素的引用,从而使得下标可以出现在赋值运算符的任意一侧
2. 一般会定义两个版本:
- 返回普通引用。
- 类的常量成员,并返回常量引用以确保不会给返回的对象赋值。
class StrVec
{
public:
std::string& operator[](std::size_t n)
{
return elements[n]; }
const std::string& operator[](std::size_t n) const
{
return elements[n]; }
private:
std::string *elements; // pointer to the first element in the array
}
3. 返回常量引用时是不能给返回的对象赋值的
const StrVec cvec=svec; //把svec的元素拷贝到cvec中
//如果svec中含有元素,对第一个元素运行string的empty函数
if(svec.size()&&svec[0].empty){
svec[0]="zero"; //正确:下标运算符返回string的引用
svec[0]="Zip"; //错误;对cvec取下标返回的是常量引用
}