Operator[] 使用友元函数重载
Operator[] overloading using friend function
为什么不能将下标运算符 (operator[]) 作为友元函数重载?
Friends 不是您的 class 的扩展,只是一个关键字,表示 xy 可以访问您的 class 的私有或受保护成员。您不能以这种方式覆盖或添加功能。
The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears.
正如 Bjarne Stroustrup 在 D&E book 中所说:
However, even in the original design of C++, I restricted operators []
, ()
, and ->
to be members. It seemed a harmless restriction that eliminated the possibility of some obscure errors because these operators invariably depend on and typically modify the state of their left-hand operand. However, it is probably a case of unnecessary nannyism.
为什么不能将下标运算符 (operator[]) 作为友元函数重载?
Friends 不是您的 class 的扩展,只是一个关键字,表示 xy 可以访问您的 class 的私有或受保护成员。您不能以这种方式覆盖或添加功能。
The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears.
正如 Bjarne Stroustrup 在 D&E book 中所说:
However, even in the original design of C++, I restricted operators
[]
,()
, and->
to be members. It seemed a harmless restriction that eliminated the possibility of some obscure errors because these operators invariably depend on and typically modify the state of their left-hand operand. However, it is probably a case of unnecessary nannyism.