【问题标题】:Defining the []= operator定义 []= 运算符
【发布时间】:2012-07-20 07:56:22
【问题描述】:

我正在编写一个类 Grid,其元素是 Points - 一个 (int) 网格,每个正方形都有一个 (double) 点。我已经定义了这个(高度值存储在其他地方):

Point &operator[](Point p) { return floor(get_x(p)) + height * floor(get_y(p)); }

我想定义赋值运算符。怎么办?是根据[]运算符自动定义的吗?

目前为止

Point &operator[]=(Point p, Point q) { data[floor(get_y(p)) * height + floor(get_x(p))] = q; }

但这似乎是一个循环定义。

【问题讨论】:

  • operator[] 当然不应该返回对网格的引用!在您的定义中,它没有,但是当声明的返回类型为 Grid& 时,这将导致第一个错误。

标签: c++ arrays operator-overloading


【解决方案1】:

这不是它的工作原理,[] 运算符应该返回该索引处元素的引用,并且 element(类型)应该支持operator=(即Point::operator=

【讨论】:

  • 啊,谢谢。我以前应该看到的。所以它几乎使用了一个指针。
  • @jclancy 是否使用指针是一个实现细节。
猜你喜欢
  • 2021-06-11
  • 2013-04-14
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 2020-10-10
  • 1970-01-01
相关资源
最近更新 更多