Write a program to negate the value of the object which has matrix of elements using unary minus operator overloading.
#include <iostream>
#include <iomanip>
using namespace std;
class Matrix{
int rows, cols, mat[10][10];
void getdata(){
cout<<"Enter the matrix contents. \n";
for(int i = 0; i < this->cols; i++)
for(int j = 0; j < this->rows; j++)
cin>>mat[i][j];
}
public:
Matrix(){
rows = 0;
cols = 0;
}
Matrix(int r, int c){
this->rows = r;
this->cols = c;
this->getdata();
}
void showdata(){
if(this->rows == 0 && this->cols == 0)
cout<<endl<<"\nNo data present";
else
for(int i = 0; i < this->cols; i++){
cout<<endl;
for(int j = 0; j < this->rows; j++)
cout<<setw(3)<<mat[i][j];
}
cout<<endl;
}
Matrix operator-(){
Matrix* A = this;
for(int i = 0; i < A->cols; i++)
for(int j = 0; j < A->rows; j++)
A->mat[i][j] *= -1;
return *A;
}
};
int main(){
int rows, cols;
cout<<"Enter number of rows: ";
cin>>rows;
cout<<"Enter number of columns: ";
cin>>cols;
Matrix A(rows, cols);
A.showdata();
Matrix B = -A;
B.showdata();
return 0;
}
Comments
Leave a comment