C++ Online Compiler
Example: Matrix Addition using Operator Overloading in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Addition using Operator Overloading #include <iostream> #include <vector> // Using vector for dynamic matrices // Define constants for matrix dimensions const int ROWS = 2; const int COLS = 2; class Matrix { public: int data[ROWS][COLS]; // Store matrix elements // Constructor to initialize matrix elements Matrix() { for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLS; ++j) { data[i][j] = 0; // Initialize with zeros } } } // Constructor to initialize with values (optional, for convenience) Matrix(int arr[ROWS][COLS]) { for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLS; ++j) { data[i][j] = arr[i][j]; } } } // Overload the + operator for matrix addition Matrix operator+(const Matrix& other) const { Matrix result; // Create a new matrix for the result for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLS; ++j) { result.data[i][j] = this->data[i][j] + other.data[i][j]; } } return result; // Return the resulting matrix } // Function to display the matrix void display() const { for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLS; ++j) { std::cout << data[i][j] << " "; } std::cout << std::endl; } } }; int main() { // Step 1: Define two matrices (Matrix A and Matrix B) int arrA[ROWS][COLS] = {{1, 2}, {3, 4}}; int arrB[ROWS][COLS] = {{5, 6}, {7, 8}}; Matrix matrixA(arrA); Matrix matrixB(arrB); std::cout << "Matrix A:" << std::endl; matrixA.display(); std::cout << std::endl; std::cout << "Matrix B:" << std::endl; matrixB.display(); std::cout << std::endl; // Step 2: Add Matrix A and Matrix B using the overloaded '+' operator Matrix matrixC = matrixA + matrixB; // Step 3: Display the resulting matrix C std::cout << "Result of Matrix A + Matrix B:" << std::endl; matrixC.display(); std::endl; // Redundant, removed std::cout << std::endl; // Example with another matrix int arrD[ROWS][COLS] = {{10, 20}, {30, 40}}; Matrix matrixD(arrD); std::cout << "Matrix D:" << std::endl; matrixD.display(); std::cout << std::endl; Matrix matrixE = matrixC + matrixD; std::cout << "Result of Matrix C + Matrix D:" << std::endl; matrixE.display(); std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS