c++ - 类内的动态数组

标签 c++ class matrix dynamic-arrays

我现在正在做以下练习:

通用 Matrix 类(15 pt)

a) Create a class called Matrix, it should contain storage for M*N numbers of type double. Just like earlier, when choosing how to store your data it is often useful to know what we are going to use the data for later. In matrix operations we are going to access the different elements of the matrix based on their column and/or row, therefore it is useful to order the members of Matrix as an array. Also, we are going to need to change the size of the data stored in the matrix, therefore it should be dynamically allocated.

b) Create constructors for the matrix.

Create the following three constructors: Matrix() • Default constructor, should initialize the matrix into the invalid state.

explicit Matrix(unsigned int N) • Should construct a valid NxN Matrix, initialized as an identity matrix. (The explicit keyword is not in the syllabus, but it should be used here.)

Matrix(unsigned int M, unsigned int N) • Should construct a valid MxN Matrix, initialized as a Zero matrix. (All elements are zero.)

~Matrix() • The destructor of Matrix, should delete any dynamically allocated memory.

到目前为止,我的类(class)如下:

    class Matrix{
    private:
        int rows;
        int columns;
        double* matrix;
    public:
        Matrix();
        explicit Matrix(int N);
        Matrix(int M, int N);
        ~Matrix();
};

我的其余代码:

    Matrix::Matrix(){
    double * matrix = NULL;
}

Matrix::Matrix(int N){
    double * matrix = new double[N * N];
    this->rows = N;
    this->columns = N;

    for(int i = 0; i < N; i++){
        for(int j = 0; j < N; j++){
            if(i==j)
                matrix[i * N + j] = 1;
            else
                matrix[i * N + j] = 0;
        }
    }
}

Matrix::Matrix(int M, int N){
    double * matrix = new double[M * N];
    this->rows = M;
    this->columns = N;

    for(int i = 0; i < M; i++){
        for(int j = 0; j < N; j++)
            matrix[i * N + j] =  0;
    }
}

Matrix::~Matrix(){
    delete [] matrix;
}

我是否正确创建了动态数组和构造函数? 我稍后将在练习中使用三个不同的构造函数创建三个不同的数组。我该怎么做?如果我尝试这样的事情

Matrix::Matrix();
Matrix::Matrix(3);

Matrix::Matrix(3,4)

我收到以下错误:

Unhandeled exception at 0x773c15de in Øving_6.exe: 0xC0000005: Access violation reading location 0xccccccc0.

我做错了什么?

最佳答案

在你的构造函数中,你定义了一个局部变量

double * matrix = new double[N * N];

它隐藏了同名的成员变量,因此该成员永远不会被初始化。

你只需要将它改成

matrix = new double[N * N];

使用 this-> 进行成员访问是非常不符合 C++ 的,除非绝对有必要消除歧义(这几乎从不)

关于c++ - 类内的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15369913/

相关文章:

javascript - 在 JavaScript 中使用哪种方式来定义类

c - 如何从文件中读取矩阵?

python - 如何在numpy中对张量矩阵执行按位和运算

c++ - 如何让函数访问其他 .cpps 变量?

python - 使用 numpy 将数组元素添加到矩阵的每一列

c++ - 派生类的析构函数发生了什么?

c++ - 为自己的流类重载插入运算符

c++ - 根据非类型参数值推导出类型列表

C++ 二维指针数组

java - 如何通过抽象类实现函数指针的 Java 等价物