How to implement addition and subtraction of matrices using operator overloading in C++?
To perform addition and subtraction operations for determinants, you need to overload the addition and subtraction operators. Here is an example code:
#include <iostream>
#include <vector>
class Matrix {
private:
int rows;
int cols;
std::vector<std::vector<int>> data;
public:
Matrix(int r, int c) : rows(r), cols(c) {
data.resize(rows, std::vector<int>(cols, 0));
}
void setValue(int r, int c, int value) {
data[r][c] = value;
}
Matrix operator+(const Matrix& other) const {
if (rows != other.rows || cols != other.cols) {
throw std::runtime_error("Matrix dimensions don't match");
}
Matrix result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}
return result;
}
Matrix operator-(const Matrix& other) const {
if (rows != other.rows || cols != other.cols) {
throw std::runtime_error("Matrix dimensions don't match");
}
Matrix result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.data[i][j] = data[i][j] - other.data[i][j];
}
}
return result;
}
void print() 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() {
Matrix A(2, 2);
A.setValue(0, 0, 1);
A.setValue(0, 1, 2);
A.setValue(1, 0, 3);
A.setValue(1, 1, 4);
Matrix B(2, 2);
B.setValue(0, 0, 5);
B.setValue(0, 1, 6);
B.setValue(1, 0, 7);
B.setValue(1, 1, 8);
Matrix C = A + B;
C.print();
std::cout << std::endl;
Matrix D = A - B;
D.print();
return 0;
}
In the code above, we have defined a Matrix class to represent a determinant. In the Matrix class, we have overloaded the addition and subtraction operators to perform element-wise addition and subtraction on two Matrix objects. In the overloaded addition and subtraction operator functions, we first check if the dimensions of the two Matrix objects are the same, if not, we throw an exception. Then, we create a new Matrix object to store the result, and loop through each element to perform the corresponding addition or subtraction. Finally, we return the result Matrix object.
In the main function, we created two Matrix objects A and B, assigned values to them, and then used overloaded addition and subtraction operators to calculate A + B and A – B, printing out the results.