c++ - 定义 []= 运算符

标签 c++ arrays operator-overloading

我正在编写一个 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= (即 Point::operator=)

关于c++ - 定义 []= 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11575151/

相关文章:

c++ - 在作用域结束之前调用析构函数

java - 如何根据现在的月份检查选择的季节是否正确?

java - 如何将包含 double 值的 char 数组转换为 double 变量?

C++ 指向重载索引的箭头 ( this->[ ] )

c++ - 创建类似 OpenGL 的图形库

c++ - 为什么 STL 算法 find() 在 map 上不起作用?

c++ - 如果有一个关于流的 'overloading clash' 会发生什么?

c++ - 错误: lvalue required while operator overloading++/-- etc

c++ - 如何让我的过时代码在运行前自动构建?

ios - Swift - 将数组中的值转换为 double 或 float