In C++, must operator[] () be a member function?

依然范特西╮ 提交于 2020-01-02 07:36:26

问题


In C++, must operator []() always be a member function? If yes, why?

I read "An operator must be a member function" in book

"The C++ Programming Language Special Edition" page 287.


回答1:


From the C++ draft:

13.5.5 Subscripting [over.sub]

operator[] shall be a non-static member function with exactly one parameter. It implements the subscripting syntax

postfix-expression [ expression ]

Thus, a subscripting expression x[y] is interpreted as x.operator for a class object x of type T if T::operator exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3.3).


I can't find it explicit in the spec, but I'm assuming the reason is because it's expected to return an lvalue.

Scratch that: it didn't make sense. It returns an lvalue of the subscripted type not the object type.



来源:https://stackoverflow.com/questions/17210718/in-c-must-operator-be-a-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!