0
votes

I wrote a matrix class with overloaded operators. However, whenever I use my Matrix class in another file, my code fails to compile. Here are my files

Matrix.h file

#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 file

#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;
}

TestMatrix.cpp

#include "Matrix.h"


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

I compiled using the following command

g++ TestMatrix.cpp Matrix.cpp

and I only got this as output

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

My question is how are the overloaded operators supposed to be placed so that the compiler recognizes them?

1
You need to declare it in header file. - songyuanyao
Note that your operator+ has return type Matrix &. Currently, you return a dangling reference. - bipll
The header idea work. Thanks. Also, I fixed the reference. - Alfredo Velasco

1 Answers

0
votes

Your file TestMatrix.cpp can not see that you have defined an operator+ in another source file.

Add this to Matrix.h:

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

That is a function declaration. It declares that this function exists.