动态分配矩阵的算子重载

Operator overloading with dynamic allocated matrix

本文关键字:重载 动态分配      更新时间:2023-10-16

我正在写一些代码来自学c++。

执行以下代码:

#include <iostream>
using namespace std;
class Matrix
{
    int m, n;
    public: 
    float** value;
    Matrix(int m, int n)
    {
        value = new float*[m];
        for (int i = 0; i < m; ++i)
            value[i] = new float[n];
        this->m = m; this->n = n;
    }
    ~Matrix()
    {
        for (int i = 0; i < m; ++i)
            delete[] value[i];      
        delete[] value;
    }
    Matrix(const Matrix& A)
    {
        m = A.getLength();
        n = A.getWidth();
        value = new float*[m];
        for (int i = 0; i < m; ++i)
            value[i] = new float[n];
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                value[i][j] = A.value[i][j];    
    }
    int getLength(void) const
    {
        return m;
    }
    int getWidth(void) const
    {
        return n;
    }
    void print() const
    {
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
                cout << value[i][j] << "t";
            cout << endl;
        }
    }

    Matrix operator + (const Matrix& B)
    {
        if (m != B.getLength() || n != B.getWidth())
            return Matrix(0, 0);
        Matrix C = Matrix(m, n);
        cout << value << endl;
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                C.value[i][j] = value[i][j] + B.value[i][j];
        return C;
    }

    void operator = (const Matrix& A)
    {
        m = A.getLength();
        n = A.getWidth();
        value = new float*[m];
        for (int i = 0; i < m; ++i)
            value[i] = new float[n];
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                value[i][j] = A.value[i][j];
    }
};

int main()
{
    Matrix A = Matrix(3, 3);

    A.value[0][0] = 1; A.value[0][1] = 2; A.value[0][2] = 3;
    A.value[1][0] = 4; A.value[1][1] = 5; A.value[1][2] = 6;
    A.value[2][0] = 7; A.value[2][1] = 8; A.value[2][2] = 9;
    Matrix B = Matrix (3, 3);
    B.value[0][0] = 1; B.value[0][1] = 2; B.value[0][2] = 3;
    B.value[1][0] = 4; B.value[1][1] = 5; B.value[1][2] = 6;
    B.value[2][0] = 7; B.value[2][1] = 8; B.value[2][2] = 9;

    Matrix C = A + B;
    cout << C.value << endl;
    C.print();
    return 0;    
}

在"矩阵C = a + B"部分生成内存泄漏?我不知道关联完成后返回的矩阵是否被销毁。如果是,有办法解决吗?

In语句

Matrix C = A + B;

没有泄漏。

虽然在你的代码中没有使用复制赋值操作符,但是你的复制赋值操作符不会释放先前分配给对象矩阵的内存。复制赋值操作符与复制构造函数的不同之处在于,对象已经创建并具有分配的矩阵。你还必须检查是否有self赋值

还应该声明为

Matrix & operator = (const Matrix& A)

对于operator +,则应声明为

Matrix operator + (const Matrix& B) const;

const Matrix operator + (const Matrix& B) const;