在矩阵类中重载[]

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(以便您可以访问逻辑上为constMatrix2d的元素)。

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];

你在这里要做的是,按照这个顺序:

  1. 获取aux在位置0的float
  2. 获取mat1mat2在位置0处的float ,然后
  3. 赋和给float

注意我对"值"的强调——你所要做的实际上是试图说服编译器,例如7.0 = 3.0 + 10.0;你的编译器说"嘿,我不能给常量表达式赋值(13.0)"

这个问题的解决方案不是返回,而是返回对矩阵中条目的引用。我建议用谷歌搜索"返回引用"