Реализуй класс для хранения квадратной матрицы. перезагрузите метод + и -, сгенерируйте и обработайте ошибки
#include <iostream> #include <vector> using namespace std; class Matrix { private: int size; vector<vector<int>> data; public: Matrix(int size) : size(size) { // Initialize the matrix with all zeros data.resize(size); for (int i = 0; i < size; i++) { data[i].resize(size); for (int j = 0; j < size; j++) { data[i][j] = 0; } } } // Overload the + operator Matrix operator+(const Matrix &other) { if (size != other.size) { throw invalid_argument("Matrices must be of the same size to add them"); } Matrix result(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { result.data[i][j] = data[i][j] + other.data[i][j]; } } return result; } // Overload the - operator Matrix operator-(const Matrix &other) { if (size != other.size) { throw invalid_argument("Matrices must be of the same size to subtract them"); } Matrix result(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { result.data[i][j] = data[i][j] - other.data[i][j]; } } return result; } }; int main() { Matrix m1(3); Matrix m2(3); // Add the two matrices Matrix m3 = m1 + m2; // Subtract the two matrices Matrix m4 = m1 - m2; return 0; } Код #include <iostream> #include <vector> using namespace std; class Matrix { private: int size; vector<vector<int>> data; public: Matrix(int size) : size(size) { // Initialize the matrix with all zeros data.resize(size); for (int i = 0; i < size; i++) { data[i].resize(size); for (int j = 0; j < size; j++) { data[i][j] = 0; } } } // Overload the + operator Matrix operator+(const Matrix &other) { if (size != other.size) { throw invalid_argument("Matrices must be of the same size to add them"); } Matrix result(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { result.data[i][j] = data[i][j] + other.data[i][j]; } } return result; } // Overload the - operator Matrix operator-(const Matrix &other) { if (size != other.size) { throw invalid_argument("Matrices must be of the same size to subtract them"); } Matrix result(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { result.data[i][j] = data[i][j] - other.data[i][j]; } } return result; } }; int main() { Matrix m1(3); Matrix m2(3); // Add the two matrices Matrix m3 = m1 + m2; // Subtract the two matrices Matrix m4 = m1 - m2; return 0; }