【问题标题】:Error with overloaded operator+ C++重载运算符+ C++ 的错误
【发布时间】:2014-02-08 18:05:09
【问题描述】:

我在尝试使用重载的 operator+ 添加两个 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.
  };

我不明白这个错误的含义,如果能帮助我理解它的含义以及如何解决它,我将不胜感激。

【问题讨论】:

  • 在开始重载运算符之前,您需要学习基本的数组运算和基本的 C++。跑步前先学会爬行。更实际的是,编写一个函数add,将两个矩阵相加并返回结果:您的问题远在重载运算符之前。

标签: c++ matrix multidimensional-array operator-overloading addition


【解决方案1】:

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

应该是这样的

matrices sum(addition);
return sum;

这只是编译器错误的来源。您的代码中还有许多逻辑错误,例如我前面提到的越界数组访问,在内部 for-loop 中。您必须解决这些问题,否则会出现未定义的行为。

【讨论】:

  • 我已经试过了,但是没有用。我得到了和以前一样的错误。
【解决方案2】:

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

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

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

现在你可以这样写了:

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

【讨论】:

    猜你喜欢
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多