Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- // Задача матрица
- class Matrix {
- private:
- int** matrix;
- int rows;
- int cols;
- public:
- Matrix(int new_rows, int new_cols) {
- this->rows = new_rows;
- this->cols = new_cols;
- this->matrix = new int*[new_rows];
- for (int i = 0; i < this->rows; ++i) {
- matrix[i] = new int[new_cols];
- }
- for (int i = 0; i < this->rows; ++i) {
- for (int j = 0; j < this->cols; ++j) {
- matrix[i][j] = 0;
- }
- }
- }
- // Конструктор копирования
- Matrix(const Matrix& other) {
- rows = other.rows;
- cols = other.cols;
- matrix = new int*[rows];
- for (int i = 0; i < rows; ++i) {
- matrix[i] = new int[cols];
- for (int j = 0; j < cols; ++j) {
- matrix[i][j] = other.matrix[i][j];
- }
- }
- }
- ~Matrix() {
- for (int i = 0; i < this->rows; ++i) {
- delete[] this->matrix[i];
- }
- delete[] this->matrix;
- }
- Matrix operator+ (const Matrix& other) {
- if (this->rows == other.rows && this->cols == other.cols) {
- Matrix new_matrix(this->rows, this->cols);
- for (int i = 0; i < this->rows; ++i) {
- for (int j = 0; j < this->cols; ++j) {
- new_matrix.matrix[i][j] = this->matrix[i][j] + other.matrix[i][j];
- }
- }
- return new_matrix;
- } else {
- cout << "Разные размерности!" << endl;
- return Matrix(0, 0);
- }
- }
- // Оператор умножения
- Matrix operator* (const Matrix& other) {
- if (this->cols != other.rows) {
- cout << "Разные размерности!" << endl;
- return Matrix(0, 0);
- }
- Matrix result(this->rows, other.cols);
- for (int i = 0; i < this->rows; ++i) {
- for (int j = 0; j < other.cols; ++j) {
- result.matrix[i][j] = 0; // Initialize result element to 0
- for (int k = 0; k < this->cols; ++k) {
- result.matrix[i][j] += this->matrix[i][k] * other.matrix[k][j];
- }
- }
- }
- return result;
- }
- void print() const {
- for (int i = 0; i < this->rows; ++i) {
- for (int j = 0; j < this->cols; ++j) {
- cout << matrix[i][j] << ' ';
- }
- cout << '\n';
- }
- }
- };
- // Код для проверки
- int main() {
- Matrix mat1(2, 2);
- Matrix mat2(2, 2);
- Matrix sum = mat1 + mat2;
- sum.print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement