动态矩阵类

Dynamic matrix class

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

我需要构造一个矩阵类,并用一个特定的函数给它赋值。

下面是我的代码:

class MATRIX
{
    int row, col;
    double **p;
public:
    MATRIX(int, int);
    void Set(int, int, double);
    ~MATRIX();
};
MATRIX::MATRIX(int x, int y)
{
    row = x;
    col = y;
    p = new double*[x];
    for (int i = 0; i < x; i++)
    {
        p[i] = new double[y];
    }
}
void MATRIX::Set(int a, int b, double d)
{
    p[a][b] = d;
}
    MATRIX::~MATRIX()
{
    for (int i = 0; i < row; i++)
        delete[] p[i];
    delete[] p;
}
int main()
{
    MATRIX A(2, 3); // Initializes a matrix with size 2x3
    MATRIX B(7, 4); // Initializes a matrix with size 7x4
    A.Set(1, 2, 4.7); // Sets the value of A[1][2] to 4.7
    B.Set(0, 3, 2.9); // Sets the value of B[0][3] to 2.9
}

Set函数中,我在调试器中看到这个:

this->p was 0x1110112

我该如何修复它?

因为这是c++,这看起来更像C。也许一个好的第一步是编辑一些代码。我建议您将c风格的数组更改为std::数组或std::vector。头文件应该是这样的:

template<typename T, std::size_t rows, std::size_t columns> 
class MATRIX
{
    std::array<std::array<T, columns>, rows> matrix_data;
public:
    MATRIX();
    void Set(int, int, double);
    ~MATRIX();
};

这使用了一个模板类,这意味着你必须在主

中做这样的操作
MATRIX<double, 2, 3> A;

我没有时间写完整的代码,但我认为这将使你开始!古德勒克!