gpt4 book ai didi

c++ - 类内的动态数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:28 27 4
gpt4 key购买 nike

我现在正在做以下练习:

通用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com