I see this topic has been hacked to death but it seems to be slightly different in each case. Anyway, I've been chopping away at this code for awhile. I realize that it is easier to overload the () rather than the [] which is what I was determined to do at first. Anyway, so now that I've switched to (), my program can compile BUT I'm getting weirdo numbers. And now that I have no compiler errors to go over, I'm not sure where to start debugging.
Also, I don't quite understand how my operator() functions are working but I know they are necessary to overload () instead of [].
(Note: ignore the overloading functions. I'm sure I can get those to work once I've gotten my matrix to display correctly)
Any clarification and help is greatly appreciated!
This is my header file:
#include <iostream>
#include <limits.h>
using namespace std;
class Matrix
{
friend ostream& operator<<(ostream& out, const Matrix& m);
friend Matrix operator-(const Matrix& m1, const Matrix & m2);
friend Matrix operator*(const Matrix& m1, const Matrix & m2);
friend Matrix operator++(const Matrix& m1);
friend Matrix operator--(const Matrix& m1);
friend void setMatrix(Matrix&, int);
public:
Matrix(unsigned int r, unsigned int c);
int& operator() (unsigned row, unsigned col);
int operator() (unsigned row, unsigned col) const;
~Matrix();
//int getrows() const;
//int getcols() const;
Matrix operator+(const Matrix & m2);
private:
int rows;
int cols;
unsigned rows_;
unsigned cols_;
int *info;
};
This is my implementation file:
#include "Matrix.h"
#include <iostream>
using namespace std;
int rows, cols;
ostream& operator<<(ostream& out, const Matrix& m)
{
for(int i=0; i<m.rows; i++)
{
for(int j=0; j<m.cols; j++)
{
out<<m.info[i*m.cols+j];
}
out<<endl;
}
return out;
}
Matrix operator-(const Matrix& m1, const Matrix& m2)
{
rows=m1.rows-m2.rows;
cols=m1.cols-m2.cols;
return Matrix(rows, cols);
}
Matrix operator*(const Matrix& m1, const Matrix& m2)
{
rows=m1.rows*m2.rows;
cols=m1.cols*m2.cols;
return Matrix(rows, cols);
}
Matrix::Matrix(unsigned int r, unsigned int c)
:rows(r), cols(c)
{
info=new int[r*c];
}
Matrix::~Matrix()
{
delete[] info;
}
int& Matrix::operator() (unsigned row, unsigned col)
{
if (row >= rows_ || col >= cols_)
return info[cols_*row + col];
}
int Matrix::operator() (unsigned row, unsigned col) const
{
if (row >= rows_ || col >= cols_)
return info[cols_*row + col];
}
//int Matrix::getrows() const
// {
// return rows;
//}
//int Matrix::getcols() const
// {
// return cols;
//}
And this is my very simple driver for now:
#include "Matrix.h"
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
Matrix M(4,3);
M(0,0) = 25; M(0,1) = 7; M(0,2) = 42;
M(1,0) = 38; M(1,1) = 85; M(1,2) = 21;
M(2,0) = 14; M(2,1) = 65; M(2,2) = 92;
M(3,0) = 47; M(3,1) = 55; M(3,2) = 10;
cout<<M<<endl;
system("pause");
return 0;
}