在矩阵类中重载[]
Overloading [] in matrix class
本文关键字:重载 更新时间:2023-10-16
我试图重载运算符[],这样我就可以直接访问矩阵,而不是使用数组。
我做了什么:
. h:
#include <array>
#include "vector.h"
using namespace std;
struct Matrix2d{
array<float,4> positions;
//Constructors
Matrix2d(float x11, float x12, float x21, float x22);
float operator[](int index);
....
. c:
float Matrix2d::operator[](int index){
return this->positions[index];
}
Matrix2d operator+(Matrix2d& mat1, Matrix2d& mat2){
Matrix2d aux(0, 0, 0, 0);
aux[0] = mat1[0] + mat2[0];
aux[1] = mat1[1] + mat2[1];
aux[2] = mat1[2] + mat2[2];
aux[3] = mat1[3] + mat2[3];
return aux;
}
发生的是aux[i]给出一个错误"必须是一个可修改的左值",但如果我做aux。position [i]它工作
我已经看到了这个参考,它工作,所以我不明白为什么我的版本不工作…
救援参考文献
您需要从operator[]
返回对容器内元素的引用,以便能够从外部修改该给定元素。
当前您正在返回所需元素的临时副本,正如您的问题—所述—不允许进行此类修改,然而,当只想读取值时,它是完全可以的(因为在这种情况下您不关心复制)。
提出决议
修复就像将&
附加到上述操作符的返回类型一样简单,但请注意,您可能应该添加相同函数的const-overload(以便您可以访问逻辑上为const
的Matrix2d
的元素)。
struct Matrix2d {
...
float& operator[](int index);
// float const& operator[] (int index) const
// ^- you probably also want this
...
};
float& Matrix2d::operator[](int index){
return this->positions[index];
}
让我们看看这个:
aux[0] = mat1[0] + mat2[0];
你在这里要做的是,按照这个顺序:
- 获取
aux
在位置0的float
值, - 获取
mat1
和mat2
在位置0处的float
值,然后 - 赋和给float 值。
注意我对"值"的强调——你所要做的实际上是试图说服编译器,例如7.0 = 3.0 + 10.0
;你的编译器说"嘿,我不能给常量表达式赋值(13.0)"
这个问题的解决方案不是返回值,而是返回对矩阵中条目的引用。我建议用谷歌搜索"返回引用"
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 重载==不适用于二进制树
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 正在尝试重载二进制搜索树分配运算符
- 重载Singly Linked List中的赋值运算符
- 取消引用运算符不能重载