无法识别重载的运算符。错误 2

Overloaded operators not recognized. Error 2

我用重载运算符写了一个矩阵 class。但是,每当我在另一个文件中使用 Matrix class 时,我的代码都无法编译。这是我的文件

Matrix.h 文件

#include <vector>
#include <iostream>

#ifndef _MATRIX_H
#define _MATRIX_H

class Matrix {
private:
  int row, col;
public:
  std::vector<std::vector<double>> matrix;
  Matrix(int);
  ~Matrix();
  int getRows() const { return row; }
  int getCols() const { return col; }
  std::vector<double>& operator[](int index){
    return matrix.at(index);
  }

  Matrix& operator+=(const Matrix& b){
    if(row != b.getRows() || col != b.getCols()){
      std::cerr << "Mismatched dimensions for +" << std::endl;
      std::cerr << "A is " << row << "x" << col << std::endl;
      std::cerr << "B is " << b.getRows() << "x" << b.getCols() << std::endl;
      throw std::exception();
    }
    for(int i = 0; i < this->row; i++){
      for(int j = 0; j < this->col; j++){
        this->matrix[i][j] += b.matrix[i][j];
      }
    }
    return *this;
  }


};

#endif

Matrix.cpp 文件

#include "Matrix.h"

/**
* This constructor takes in a single positive integer n and
* makes an nxn sized matrix.
*/
Matrix::Matrix(int size){
  if(size <= 0){
    std::cerr << "Invalid size: " << size << std::endl;
    std::cerr << "Sizes must be greater than 0!" << std::endl;
    throw std::exception();
  }
  row = size;
  col = size;
  matrix.resize(size);
  for(int i = 0; i < size; i++){
    std::vector<double> newVector(size);
    matrix[i] = newVector;
    for(int j = 0; j < size; j++){
      matrix[i].push_back(0);
    }
  }
}


Matrix::~Matrix() {
}

Matrix& operator+(Matrix a, const Matrix& b){
  return a += b;
}

测试Matrix.cpp

#include "Matrix.h"


int main(){
  Matrix a(2);
  Matrix b(2);
  a + b;
  return 0;
}

我使用以下命令编译

g++ TestMatrix.cpp Matrix.cpp

我只得到这个作为输出

TestMatrix.cpp: In function ‘int main()’: TestMatrix.cpp:8:9: error: no match for ‘operator+’ (operand types are ‘Matrix’ and ‘Matrix’) a + b; ^

我的问题是应该如何放置重载运算符以便编译器识别它们?

您的文件TestMatrix.cpp看不到您在另一个源文件中定义了一个operator+

将此添加到 Matrix.h:

Matrix operator+(Matrix a, const Matrix& b);

那是一个函数声明。它声明这个函数存在。