c++ operator overloads matrix
I tried to do it using proxy class, but I need to solve the assignment without proxy.
Here is the code. I've been helped by some here but I'm pretty sure it is wrong.
This is the given "main.cpp".
1 2 3 4 5 6 7 8 9 10
|
void main()
{
Matrix theMat(4,2);
theMat[1][1]=234;
theMat[0][0]=234;
cout << theMat;
const Matrix s =-theMat;
cout << theMat << endl << s << endl;
theMat = s + 12 * -theMat * theMat * 25 - s;
}
| |
This is the Matrix.h.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#ifndef MATRIX_H
#define MATRIX_H
class Matrix
{
public :
Matrix(int ,int );
friend ostream& operator<<(ostream& os, const Matrix& matrix); /// cant print all matrix values
int const* operator[]( int const y ) const;
int* operator[]( int const y );
private :
int numOfRows;
int numOfCols;
int **matrix;
};
#endif
| |
Matrix.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include "Matrix.h"
using namespace std;
Matrix::Matrix(int rows,int cols)
:numOfRows(rows),numOfCols(cols)
{
matrix=new int *[cols];
for(int i=0;i<rows;i++)
{
matrix[i]=new int [cols];
for(int c=0;c<cols;c++)
{
matrix[i][c]=0;
}
}
}
ostream& operator<<(ostream& os, const Matrix& matrix)
{
return os;
}
int* Matrix:: operator[]( int const y );
{
return &matrix[0][y];
}
int Matrix::const* operator[]( int const y ) const;
{
return &matrix[0][y];
}
| |
Last edited on
you can use std::vector<std::vector<int> > to replace int **, and you will have a synthesized operator= by compiler.
Topic archived. No new replies allowed.