重载运算符 + C++ 时出错

Error with overloaded operator+ C++

本文关键字:出错 C++ 运算符 重载      更新时间:2023-10-16

我在尝试使用重载运算符+添加两个 2D 矩阵时遇到问题。我已经成功地将两个矩阵分配给两个不同的数组。

我的错误是:

在函数 'mathadd::matrices mathadd::operator+(mathadd::matrices&, mathadd::matrices&)' 中:

调用"mathadd::matrices::matrices(double&)"没有匹配函数

候选人是: MathAdd::Matrices::

Matrices(const mathadd::matrices&)

在我的 int main() {} 中,此错误的主要部分是:

matrices sample;
double array1[4][4], array2[4][4], add[4][4];
add[4][4] = array1[4][4] + array2[4][4];

重载运算符定义为:

     matrices operator +(matrices& p1, matrices& p2)
      {
           double addition[4][4];
           for (int y = 0; y < 4; ++y )
           {
               for (int x = 0; x < 4; ++x )
               {
                    addition[4][4] = p1.get_array1() + p2.get_array2();
               }
            }
            matrices sum(addition[4][4]); // This is where the error is.
            return sum;
      }

我的班级看起来像这样

class matrices
  {
        public:
               matrices();
               void assignment(double one[4][4], double two[4][4]);
               double get_array1() const {return first_array[4][4];}
               double get_array2() const {return second_array[4][4];} 
               matrices operator +(matrices& p1, matrices& p2);
        private:
                double first_array[4][4], second_array[4][4];
                //Initialized to 0 in constructor.
  };

我不明白这个错误是什么意思,我将不胜感激任何帮助,以了解它的含义以及如何修复它。

addition[4][4] 是一个双重越界数组访问,用于从 addition 命名的第五个double[]获取第五个double。只需将名称传递addition而不是addition[4][4] matrices sum(addition[4][4]).

所以应该是

matrices sum(addition);
return sum;

这只是编译器错误的根源。代码中也有许多逻辑错误,例如我前面提到的内部for -循环中的越界数组访问。您将不得不修复这些问题,否则将获得未定义的行为。

您会收到错误,因为您的operator +是为 matrices 类型的对象定义的,而不是为 double 秒的 2D 数组定义的。您需要在添加矩阵之前构造矩阵,如下所示:

首先,为matrices添加一个需要double[4][4]的构造函数。然后,将operator +的签名更改为static,并对其参数进行const引用:

static matrices operator +(const matrices& p1, const matrices& p2);

现在你可以这样写:

matrices add = matrices(array1) + matrices(array2);