c++ - 在 C++ 中重载运算符给我一个错误

标签 c++ overloading operator-keyword

当我尝试在 main.cpp 中使用这一行时:

m3.array = m1.array+m2.array;

其中 m3、m1 和 m2 都是类类型 Matrix 的对象,具有一个 int[3][3] 数组 - 我不断收到一个错误,处理类型 int[3][3] 和 int[3][3] 到操作数“+”的不兼容赋值。我不知道确切的错误,因为我不在电脑前编译程序。

这是我的 matrix.cpp:

#include <iostream>
#include <string>
#include "matrix.h"

using namespace std;

Matrix::Matrix()
{
    m1.array = 0;
}

istream& opeator >>(istream& inp, Matrix& m1)
{
         int i, j;

         for (i = 0; i < 3;i++)
         {
             for (j=0; j < 3;j++)
             {
                 inp >> m1.array[i][j];
             }
         }
         return inp;
}
ostream& operator <<(istream& outp, Matrix& m1)
{
         int i, j;
         for (i = 0;i<3;i++)
         {
             for (j = 0;j<3;j++)
             {
                 out<<m1.array[i][j]<<" "<<endl;
             }
         }
         return outp;
}

Matrix operator + (const Matrix& m1, const Matrix& m2)
{
        Matrix answer;
        int i,j;
        for (i = 0;i<3;i++)
        {
            for (j = 0;j<3;j++)
            {
                answer.array[i][j] = m1.array[i][j] + m2.array[i][j];
            }
        }
        return answer;
}

Matrix operator - (const Matrix& m1, const Matrix& m2)
{
        Matrix answer;
        int i, j;
        for (i = 0;i<3;i++)
        {
            for (j = 0;j<3;j++)
            {
                answer.array[i][j] = m1.array[i][j] - m2.array[i][j];
            }
        }
        return answer;
}

Matrix operator * (const Matrix& m1, const matrix& m2)
{
       Matrix answer;
       int i, j, k;
       for (i = 0;i<3;i++)
       {
           for (j = 0; j<3;j++)
           {
               for (k = 0; k<3;k++)
               {
                   answer.array[i][j] = m1.array[i][k] + m2.array[k][j];
               }
           }
       }
       return answer;
}

和 matrix.h:

#ifndef MATRIX_H
#define MATRIX_H

using namespace std;

class Matrix
{
      public:
             Matrix();
             friend istream& operator >>(istream&, Matrix&);
             friend ostream& operator <<(ostream&, const Matrix&);
             friend Matrix& operator +(const Matrix&, const Matrix&);
             friend Matrix& operator -(const Matrix&, const Matrix&);
             friend Matrix& operator *(const Matrix&, const Matrix&);
             int array[3][3];

};




#endif

最佳答案

Matrix operator + (const Matrix& m1, const Matrix& m2)

这告诉计算机如何添加两个 Matrix 对象,干得好。

m3.array = m1.array+m2.array;

m1m2Matrix 对象,但 m1.array 不是。 是一个 int[3][3] 对象。幸运的是,修复非常非常简单:

m3 = m1 + m2;

关于c++ - 在 C++ 中重载运算符给我一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589622/

相关文章:

c++ - 应用于基类列表的覆盖函数

c++ - 继承重载函数 : Requires namespace?

c++ - 有没有办法动态更改比较运算符?

javascript - 运算符 '!' 无法应用于类型为 '<null> 的操作数

c++ - 如何在 C++ 中编写自定义输入流

c++ - 为返回的引用分配空间

c++ - 绑定(bind) 1 次复制构造函数调用

haskell - "overloading"能否通过 FlexibleInstances 返回不同的类型,或者匹配类型类?

python - = 和 == 有什么区别?

c++ - 查找二维 vector 中的连续字符