I am new to c++ and templates is definitely not friendly in syntax. Basically, here are some of the functions i've written, tested, and finished. Just one quick question, i've been trying for hours to write a non-member operator- overload for my matrix class and have been getting all types of syntax errors. So, where do I start?
Here is my myMatrix.h:
#ifndef MYMATRIX_H
#define MYMATRIX_H
#include <exception>
#include <vector>
#include <iostream>
using namespace std;
/* I'm using this matrix to store data */
template<typename T>
using twoD = std::vector<std::vector<T>>;
template<class T>
class Matrix{
private:
int rows;
int cols;
twoD<T> matrix;
protected:
void validSizeCheck(int rows, int cols);
public:
Matrix(int rows, int cols);
Matrix(int rows, int cols, twoD<T> newMatrix);
twoD<T> getMatrix();
int getRows();
int getCols();
void printMatrix();
void operator=(const Matrix<T> &);
Matrix<T> &operator+=(const Matrix<T> &);
Matrix<T> operator+(const Matrix<T> &);
Matrix<T> operator*(const Matrix<T> &);
Matrix<T> operator*(const T &);
};
Here is one of the thing I tried:
template <class T>
Matrix<T> operator-(const Matrix<T>& lhs,const Matrix<T>& rhs){
if(lhs.rows != rhs.cols || lhs.rows != rhs.cols{
throw exception();
}
Matrix tmp(lhs.rows, lhs.cols);
for(int i = 0; i < lhs.rows; i++){
for(int j = 0; j < cols; j++){
tmp.matrix[i][j] = lhs.matrix[i][j]+rhs.matrix[i][j];
}
}
return tmp;
}
Obviously that didn't work.. So what are the syntax that I should be following for this? Also, this might be a very dumb question but should the non-member function be in the header file or the .cpp file? So far, everything that I wrote has been in the .h file as they're all templates..
Any help would be greatly appreciated.
UPDATED: I finally got the code to works, for class & function declaration, I added this:
template<class T>
class Matrix{
private:
...
protected:
...
public:
...
template<class U>
friend Matrix<U> operator-(const Matrix<U>& lhs, const Matrix<U>& rhs);
};
Here is the function definition:
template <class U>
Matrix<U> operator-(const Matrix<U>& lhs,const Matrix<U>& rhs){
if(lhs.rows != rhs.cols || lhs.rows != rhs.cols){
throw exception();
}
Matrix<U> tmp(lhs.rows, lhs.cols);
for(int i = 0; i < lhs.rows; i++){
for(int j = 0; j < lhs.cols; j++){
tmp.matrix[i][j] = lhs.matrix[i][j]-rhs.matrix[i][j];
}
}
return tmp;
}
works perfect, no warning! Thanks for all the helps