Hello, I am making a matrix class with basic operations like addition, subtraction, Multiplication.
I have made a constructor that takes as input the rows and columns. I am done with
most of the functions but I am stuck with operator overloading.
Code:#include <iostream> using namespace std; class Matrix { int rows; int columns; int **matrix; public: Matrix(int r, int c) { rows = r; columns = c; matrix = new int *[rows]; for (int i = 0; i < rows; i++) matrix[i] = new int[columns]; } int GetRows() { return rows; } int GetColumns() { return columns; } void IdentityMatrix() { if (rows == columns) { for (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) { if ( i == j ) { matrix[i][j]= 1; } else { matrix[i][j]= 0; } } } else { cout<<"Rows and Columns not equal, Can make identity Matrix"; } } void ZeroMatrix() { for (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) matrix[i][j] = 0; } void DiagonalMatrix() { for (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) { if ( i == j ) { continue; } else { matrix[i][j]= 0; } } } void SetValues() { for (int i = 0; i< rows; i++) for (int j = 0; j< columns ;j++) cin>>matrix[i][j]; } int GetNumber(int i, int j) { return matrix[i][j]; } void SetNumber(int i, int j , int number) { matrix[i][j] = number; } void ScalarMultiplication(int number) { for (int i = 0; i< rows; i++) { for (int j = 0; j< columns ;j++) { matrix[i][j] = number*matrix[i][j]; } } } Matrix operator + (Matrix &a, Matrix &b) I am getting error here, Like I know whenever I create the object, I will have to mention the rows and columns, But i cant figure out how here?? { //if rows and coulmns of b are equal then //add them and store the result in result matrix Matrix result; for (int i = 0; i< rows; i++) { for (int j = 0; j< columns ;j++) { result[i][j] = a[i][j] + b[i][j]; } } return result; } void operator = (Matrix a, Matrix b) { //if a and b are equal //then assign b to a for (int i = 0; i< rows; i++) { for (int j = 0; j< columns ;j++) { a[i][j] = b[i][j]; } } } void Print() { for (int i = 0; i< rows; i++) { for (int j = 0; j<columns ;j++) { cout<<matrix[i][j]; cout<<" "; } cout<<endl; } } }; int main() { Matrix matrix(4,6); matrix.SetValues(); Matrix matrix2(4,6); matrix.SetValues(); Matrix c(4,6); c = matrix + matrix2; c.Print(); cout<<endl; cout<<matrix.GetNumber(3,3); cout<<endl; matrix.SetNumber(3,3, 5); matrix.Print(); cout<<endl; matrix.ScalarMultiplication(5); matrix.Print(); cout<<endl; matrix.DiagonalMatrix(); matrix.Print(); cout<<endl; matrix.IdentityMatrix(); matrix.Print(); cout<<endl; matrix.ZeroMatrix(); matrix.Print(); cout<<endl; system("Pause"); return 0; }



LinkBack URL
About LinkBacks


