#include <iostream>
#include <string>
#include <stdio.h>
usingnamespace std;
class Matrix
//CREATES A MATRIX
{
double** m;
string name;
int rows, columns;
public:
Matrix (){}
Matrix(int r, int c, string n = "anonymous")
{
name=n;
rows = r;
columns = c;
try { m = newdouble *[rows]; } catch (exception e) { if (m==0){cout<<"error";}}
for ( int i = 0; i <rows; i++)
{
try { m[i] = newdouble [columns];} catch (exception e) { if (m[i]==0){cout<<"error";}}
}
}
~Matrix(); //~Matrix(){ cout<<"\n"<<name<<" deleted"; delete m;};
Matrix operator+ (const Matrix x)
//overload the + operator
{
if ( x.rows != this.rows )
{
cout<<"Error: Rows are not equal";
return 0;
}
if (x.columns != this.columns)
{
cout<<"Error: Columns are not equal";
return 0;
}
Matrix c( x.rows,x.columns);
for (int i = 0; i < rows; i++)
{
for (int j=0; j < columns; j++)
{
c.m[i][j] = x.m[i][j]+this.m[i][j];
}
}
}
...
...
}
I get a strange error in the lines 33 and 38 as shown below, which says " In member function `Matrix Matrix::operator+(Matrix)': `rows' is not a type request for member of non-aggregate type before ')' token . conversion from `int' to non-scalar type `Matrix' requested "
and similarly same error for column variables too.
rows and columns are the members of class Matrix and since x is a parameter of type Matrix, there shouldn't be any reason why i shouldn't be able to access the private variable from its member function
1 2 3 4 5 6 7 8 9 10
if ( x.rows != this.rows )
{
cout<<"Error: Rows are not equal";
return 0;
}
if (x.columns != this.columns)
{
cout<<"Error: Columns are not equal";
return 0;
}
operator+() should take its parameter by const& and the member function itself should be const. Also it does not appear to return anything.
The default constructor does not initialize the m pointer to anything.
Catch by const reference, not by value.
Your catch block appears to try to catch out-of-memory errors. Two things:
1) If you are out of memory, be aware that operator<<() may also attempt to allocate memory, so your cout could itself throw.
2) std::bad_alloc is throw on new failure. Catch that and then you don't have to check the pointer. Because if you want to check the pointer, you have to assign it 0 before doing the new[], because in the event that new throws, m will contain its original value, which is undefined since you don't pre-initialize it.