简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM