rippy
rippy

Reputation: 195

C++ program to add and multiply 2 matrices

I have written this code in c++ to add and multiply 2 matrices using operator overloading. When i execute the code it generates errors at line 57 and 59, illegal structure operation(same error on both the lines). Please explain my mistake. Thanks in advance :)

class matrix{
public:
int i, j, row, col, mat[10][10];
void input();
matrix operator+(matrix mm2);
matrix operator*(matrix mm2);
void output();
};
void matrix::input(){
cout<<"\nEnter number of rows and columns : ";
cin>>row>>col;
cout<<"\nEnter the elements : ";
for(i=0; i<row; i++){
    for(j=0;j<col;j++){
        cin>>mat[i][j];
    }
}
}
matrix matrix::operator+(matrix mm2){
matrix temp;
temp.row=row;
temp.col=col;
for(i=0; i<temp.row; i++){
    for(j=0; j<temp.col; j++){
        temp.mat[i][j]=mat[i][j]+mm2.mat[i][j];
    }
}
return temp;
}
matrix matrix::operator*(matrix mm2){
matrix temp;
temp.row=row;
temp.col=col;
for(i=0; i<temp.row; i++){
    temp.mat[i][j]=0;
    for(j=0; j<temp.col; j++){
        temp.mat[i][j]+=mat[i][j]*mm2.mat[i][j];
    }
}
return temp;
}
void matrix::output(){
cout<<"Matrix is : ";
for(i=0;i<row;i++){
    for(j=0;j<col;j++){
        cout<<mat[i][j]<<"\t";
    }
    cout<<"\n";
}
}
int main(){
matrix m1, m2, m3;
clrscr();
m1.input();
m2.input();
m3=m1+m2;
cout<<"\nSum is "<<m3.output();
m3=m1*m2;
cout<<"\nProduct is "<<m3.output();
getch();
return 0;
}

Upvotes: 0

Views: 2023

Answers (2)

herohuyongtao
herohuyongtao

Reputation: 50667

output() is a function, you cannot put it directly on cout stream. Just call it in seperate lines.

Change

cout<<"\nSum is "<<m3.output();
...
cout<<"\nProduct is "<<m3.output();

To

cout<<"\nSum is ";
m3.output();
...
cout<<"\nProduct is ";
m3.output();

Alternatively, you can overload << operator for matrix class. Then you can do

cout<<"\nSum is "<<m3;
...
cout<<"\nProduct is "<<m3;

Upvotes: 2

macroland
macroland

Reputation: 1035

Common mistakes:

matrix matrix::operator+(matrix mm2) should be matrix matrix::operator+(const matrix& mm2){. Furthermore, this will cause you unexpected behaviours since you dont have a copy constructor.

Here is a another way of overloading the operator+, concept can be extended to other operators:

//declared as friend
template <class T> CMatrix<T> operator+(const CMatrix<T>& a, const CMatrix<T>& b)
{
    unsigned int a_row=a.m_row;unsigned int a_col=a.m_column;
    unsigned int b_row=b.m_row;unsigned int b_col=b.m_column;
    if(a_row!=b_row||a_col!=b_col) throw "Dimensions do not agree";
    CMatrix<T> addition(a_row,b_col);
    T temp=0;
    for(unsigned int i = 0; i <a_row; i++ )
        for(unsigned int j = 0; j < b_col; j++ )
        {
            T temp1=a.GetCellValue(i,j);
            T temp2=b.GetCellValue(i,j);
            temp=temp1+temp2;
            addition.SetCellValue(i,j,temp);
        }

    return addition;
}

Upvotes: 0

Related Questions