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 simpler matrix representation class Matrix { private: int rows; int cols; std::vector<std::vector<int>> data; public: // Constructor Matrix(int r, int c) : rows(r), cols(c) { data.resize(rows, std::vector<int>(cols)); } // Function to set matrix elements void setElement(int r, int c, int value) { if (r >= 0 && r < rows && c >= 0 && c < cols) { data[r][c] = value; } else { std::cout << "Error: Index out of bounds." << std::endl; } } // Function to get matrix elements (optional, for completeness) int getElement(int r, int c) const { if (r >= 0 && r < rows && c >= 0 && c < cols) { return data[r][c]; } else { std::cout << "Error: Index out of bounds." << std::endl; return 0; // Return a default value or throw an exception } } // Overload the + operator for matrix addition Matrix operator+(const Matrix& other) const { if (rows != other.rows || cols != other.cols) { std::cout << "Error: Matrix dimensions must be the same for addition." << std::endl; // Return a default empty matrix or throw an exception return Matrix(0, 0); } Matrix result(rows, cols); 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; } // 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] << "\t"; } std::cout << std::endl; } } }; int main() { // Step 1: Create two Matrix objects Matrix A(2, 3); Matrix B(2, 3); // Step 2: Set elements for Matrix A A.setElement(0, 0, 1); A.setElement(0, 1, 2); A.setElement(0, 2, 3); A.setElement(1, 0, 4); A.setElement(1, 1, 5); A.setElement(1, 2, 6); // Step 3: Set elements for Matrix B B.setElement(0, 0, 7); B.setElement(0, 1, 8); B.setElement(0, 2, 9); B.setElement(1, 0, 10); B.setElement(1, 1, 11); B.setElement(1, 2, 12); std::cout << "Matrix A:" << std::endl; A.display(); std::cout << std::endl; std::cout << "Matrix B:" << std::endl; B.display(); std::cout << std::endl; // Step 4: Add matrices using the overloaded + operator Matrix C = A + B; std::cout << "Matrix A + B (Resultant Matrix C):" << std::endl; C.display(); std::cout << std::endl; // Example of incompatible matrix addition Matrix D(2,2); D.setElement(0,0,1); D.setElement(0,1,1); D.setElement(1,0,1); D.setElement(1,1,1); std::cout << "Attempting to add Matrix A (2x3) and Matrix D (2x2):" << std::endl; Matrix E = A + D; // This will trigger the error message E.display(); // Will display an empty matrix if dimensions mismatch return 0; }
Output
Clear
ADVERTISEMENTS