#include <iostream>
#include <vector>

using namespace std;

class Matrix {
private:
    int M, N;
    vector<vector<int>> data;
public:
    Matrix(int m, int n) : M(m), N(n) {
        data.resize(M, vector<int>(N));
    }

    Matrix(const Matrix& other) {
        M = other.M;
        N = other.N;
        data = other.data;
    }

    Matrix operator+(const Matrix& other) const {
        Matrix res(M, N);
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                res.data[i][j] = data[i][j] + other.data[i][j];
            }
        }
        return res;
    }

    Matrix operator-(const Matrix& other) const {
        Matrix res(M, N);
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                res.data[i][j] = data[i][j] - other.data[i][j];
            }
        }
        return res;
    }

    Matrix& operator++() {
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                data[i][j]++;
            }
        }
        return *this;
    }

    Matrix operator++(int) {
        Matrix res(*this);
        operator++();
        return res;
    }

    Matrix& operator--() {
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                data[i][j]--;
            }
        }
        return *this;
    }

    Matrix operator--(int) {
        Matrix res(*this);
        operator--();
        return res;
    }

    bool operator==(const Matrix& other) const {
        if (M != other.M || N != other.N) {
            return false;
        }
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                if (data[i][j] != other.data[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }

    bool operator!=(const Matrix& other) const {
        return !(*this == other);
    }

    friend istream& operator>>(istream& is, Matrix& mat) {
        for (int i = 0; i < mat.M; i++) {
            for (int j = 0; j < mat.N; j++) {
                is >> mat.data[i][j];
            }
        }
        return is;
    }

    friend ostream& operator<<(ostream& os, const Matrix& mat) {
        for (int i = 0; i < mat.M; i++) {
            for (int j = 0; j < mat.N; j++) {
                os << mat.data[i][j] << ' '; 
            }
            os << endl;
        }
        return os;
    }
};

测试代码:

int main() {
    Matrix mat1(2, 2), mat2(2, 2);
    cin >> mat1 >> mat2;
    cout << mat1 << endl << mat2 << endl;

    Matrix mat3 = mat1 + mat2;
    cout << mat3 << endl;

    Matrix mat4 = mat1 - mat2;
    cout << mat4 << endl;

    ++mat1;
    cout << mat1 << endl;

    --mat2;
    cout << mat2 << endl;

    cout << (mat1 == mat2) << endl;
    cout << (mat2 != mat3) << endl;

    return 0;
}
C++ 矩阵类实现:重载运算符实现矩阵加减、输出输入、自增自减、比较

原文地址: https://www.cveoy.top/t/topic/nRnM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录