cout(<<)重载运算符,不打印减去的矩阵

时间:2018-10-06 13:22:37

标签: c++ matrix

我试图将两个矩阵相减,并以这种格式打印它们cout <<(mat1-mat2)<< endl;但是cout无法正常工作,当我打印一个矩阵时

这是代码

   #include <iostream>
   #include <iomanip>
   using namespace std;

     struct matrix {
        int** data;
         int row, col;
      };

  void createMatrix (int row, int col, int num[], matrix& mat) {
       mat.row = row;
       mat.col = col;
       mat.data = new int* [row];

      for (int i = 0; i < row; i++)
           mat.data[i] = new int [col];

      for (int i = 0; i < row; i++){
          for (int j = 0; j < col; j++){
              mat.data[i][j] = num[i * col + j];
      }}} ;

这是某人告诉我使用我执行的“ const”函数,但仍无法正常工作

ostream& operator<< (ostream& out  ,const matrix&  mat ) {

    for (int i =0 ; i< mat.row ; i++) {
         for (int j =0 ; j < mat.col ; j++) {
             out << mat.data [i] [j] << " " ;
    }
    cout << endl ;
   }
  return out ;
 };

当我使用此功能打印它时,它可以正常工作,但不能在主窗口中工作

    matrix operator-  (matrix mat1, matrix mat2) {
         matrix  matt  ;
         if ((mat1.row == mat2.row) && (mat1.col == mat2.col)) {;
              for (int i =0 ; i< mat1.row ; i++) {
                    for (int j =0 ; j < mat1.col ; j++) {
                        matt.data[i][j] = ((mat1.data [i][j]) - (mat2.data [i][j]))  ;
                        }
                        }}

       else {
         cout  << " the matrixs dont have the same dimensions " << endl ;
         }
return matt ;
 };




   int main()  {
  int data1 [] = {1,2,3,4,5,6,7,8};
  int data2 [] = {13,233,3,4,5,6};
  int data3 [] = {10,100,10,100,10,100,10,100};

matrix mat1, mat2, mat3;
createMatrix (4, 2, data1, mat1);
createMatrix (2, 3, data2, mat2);
createMatrix (4, 2, data3, mat3);

 cout << mat1 << endl;
 cout << mat2 << endl;
 cout << mat3 << endl;

 cout << ( mat3 - mat1 ) << endl ;

};

1 个答案:

答案 0 :(得分:0)

不要按引用发送矩阵,那样按值发送矩阵,则不必将其作为常量传递

ostream& operator<< (ostream& out  ,matrix  mat ) {

for (int i =0 ; i< mat.row ; i++) {
     for (int j =0 ; j < mat.col ; j++) {
         out << mat.data [i] [j] << " " ;
}
cout << endl ;
}
return out;
};