首页 > 解决方案 > 了解编写重载函数的代码(矩阵运算中的新 int[])

问题描述

昨天我们的讲师在没有任何有意义的解释的情况下给了我们下面的代码。我们正在努力理解它是如何工作的。

class Matrix {
    static int mem;
    int rows, cols;
    int* ptr;

public:
Matrix(int l = 10, int k = 10) :rows(l), cols(k) {
    ptr = new int[rows * cols];
    mem += (rows * cols) * sizeof(int);
}

Matrix(const Matrix& x) :rows(x.rows), cols(x.cols) {
    ptr = new int[rows * cols];
    int* tmp = ptr;  // HERE
    mem += (rows * cols) * sizeof(int);
    for (int i = 0; i < x.rows * x.cols; i++) {
        ptr[i] = x.ptr[i];
    }
}

~Matrix() {
    mem -= (rows * cols) * sizeof(int);
    delete[] ptr;
}

friend istream& operator>>(istream& input, Matrix& x) {
    int* tmp = x.ptr;
    for (int i = 0; i < x.rows; i++) {
        for (int j = 0; j < x.cols; j++) {
            input >> *tmp; tmp++;
        }
    }
    return input;
}

friend ostream& operator<<(ostream& output, Matrix& x) {
    int* tmp = x.ptr;
    for (int i = 0; i < x.rows; i++) {
        for (int j = 0; j < x.cols; j++) {
            output << *tmp << " "; tmp++;
        }
        output << endl;
    }
    return output;
}

friend Matrix operator+(const Matrix& x, const Matrix& y) {
    Matrix tmp(x.rows,x.cols);
    if (x.rows != y.rows || x.cols != y.cols) {
        return tmp;
    }
    else {
        for (int i = 0; i < x.rows * x.cols; i++) {
            tmp.ptr[i] = x.ptr[i] + y.ptr[i];
        }
        return tmp;
    }
}


Matrix operator=(const Matrix& x) {
    if (x.rows != x.cols) {
        delete[] ptr;
        rows = x.rows;
        cols = x.cols;
        ptr = new int[rows * cols];
        mem += (rows * cols) * sizeof(int);
    }
    for (int i = 0; i < x.rows * x.cols; i++) {
        ptr[i] = x.ptr[i];
    }
    return *this;
}

friend Matrix operator*(const Matrix& x, const Matrix& y) {...}
};

基于这段代码,我们必须重载 '*' 运算符,它将两个矩阵相乘(例如 C = A * B)。当使用 2D 数组相当容易时,我只是无法理解它现在的工作方式,所以任何帮助都将不胜感激。

谢谢你的时间!

标签: c++arraysmatrixoperator-overloading

解决方案


推荐阅读