在C ++中,operator []()是否必须为成员函数? [英] In C++, must operator[] () be a member function?
问题描述
在C ++中,operator []()
是否必须始终是成员函数?如果是,为什么?
In C++, must operator []()
always be a member function? If yes, why?
我在书中读了运算符必须是成员函数"
I read "An operator must be a member function" in book
"C ++编程语言特别版"第287页.
"The C++ Programming Language Special Edition" page 287.
推荐答案
来自C ++草案:
13.5.5下标[over.sub]
13.5.5 Subscripting [over.sub]
operator []应该是具有一个参数的非静态成员函数.它实现了下标语法
operator[] shall be a non-static member function with exactly one parameter. It implements the subscripting syntax
postfix-expression [表达式]
postfix-expression [ expression ]
因此,如果存在T :: operator且如果重载解析机制将运算符选择为最佳匹配函数,则将下标表达式x [y]解释为类型T的类对象x的x.operator. .3).
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).
我在规范中找不到它,但是我假设原因是因为它预期会返回一个左值.
从头开始:这没有道理.它返回下标类型的左值,而不是对象类型.
Scratch that: it didn't make sense. It returns an lvalue of the subscripted type not the object type.
这篇关于在C ++中,operator []()是否必须为成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!