C++重载:重载[][]运算符
问题是是否可以重载 [ ][ ] 。
在正常情况下,比如向量<向量<整数> > ,我们正在重载 [] 运算符。
但是如果 if 给 [ ][ ] 定义了特殊含义,是否可以有这样的运算符
The question is whether it is possible to overload [ ][ ] .
Well in normal circumstances like vector< vector < int > > , we are overloading the [ ] opertor .
But in cases where if define a special meaning to [ ][ ] is it possible to have such an operator
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有特殊的 [][] 运算符;它是将运算符[]应用于另一个运算符[]的结果。
您可以通过让第一个运算符返回一个特殊的临时对象(该对象也具有 [] 运算符)来赋予 [][] 构造特殊的含义。
There is no special [][] operator; it's operator[] applied to the result of another operator [].
You can give special meaning to [][] construct by having the first operator returning a special temporary object, which also has [] operator.
不,您必须重载
[]
才能返回本身已重载[]
的值。No, you will have to overload
[]
to return a value which itself has[]
overloaded.正如其他人指出的那样,没有
[][]
运算符,它是一个[]
应用于
[]
运算符结果的运算符。在最一般的在这种情况下,第一个
[]
运算符将返回一个代理,该代理实现本身是一个
[]
运算符。在最简单的情况下,“代理”可以是
T*
,因为在 C++ 中,指针实现[]
运算符。一个更通用的实现可能是这样的:
这并不完美;如果你正在处理类类型,这是不可能的
例如,支持
container[i][j].x
行;我们不能重载
运算符。
。如果你需要支持这个,关于最好的你可以做的是在
ElementProxy
上重载operator->
,并要求客户端代码使用
->
而不是.
,即使它并不是真正的指针,智能或其他。
As others have pointed out, there is no
[][]
operator, it's a[]
operator applied to the results of a
[]
operator. In the most generalcase, the first
[]
operator will return a proxy, which implementsitself a
[]
operator. In the simplest case, the “proxy”can be a
T*
, since in C++, pointers implement the[]
operator. Amore generic implementation might be along the lines of:
This isn't perfect; if you are dealing with class types, it's impossible
to support something line
container[i][j].x
, for example; we can'toverload
operator.
. If you need to support this, about the best youcan do is overload
operator->
on theElementProxy
, and requireclient code to use
->
instead of.
, even though it's not really apointer, smart or otherwise.
有两个操作员。
要执行您想要的操作,您必须重载返回对象向量的operator[]。
There are two operators.
To do what you want you must overload operator[] which returns vector of objects.
C++中的下标运算符是[]。当您使用像“object[][]”这样的语法时,您将调用运算符 [] 来缩放第一个对象,然后调用第二个运算符 [] 覆盖第一个对象所选择的对象。
实质上,您不能重载运算符“[][]”,因为该运算符不存在。您应该在容器对象上重载下标运算符,然后也在内部对象中重载它。
The subscript operator in c++ is []. when you use a syntax like this "object[][]" you are calling the operator [] to scubscript the first object and then the second operator [] over the object selected by the first.
Substancially you can't overload the operator "[][]" because this operator does not exist. You should overload the subscript operator on the container object and then overload it also in the inner object.