C++ 类中的动态数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15369913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:18:58  来源:igfitidea点击:

Dynamic arrays inside a class

c++classmatrixdynamic-arrays

提问by Ole1991

I am doing the following exercise at the moment:

我目前正在做以下练习:

A generic Matrix class (15 pt)

通用 Matrix 类(15 磅)

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 di?erent 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.

a) 创建一个名为 Matrix 的类,它应该包含 M*N 类型双精度数的存储。就像之前一样,在选择如何存储数据时,了解我们以后将要使用的数据通常很有用。在矩阵运算中,我们将根据列和/或行访问矩阵的不同元素,因此将 Matrix 的成员作为数组进行排序很有用。此外,我们将需要更改存储在矩阵中的数据的大小,因此应该动态分配。

b) 为矩阵创建构造函数。

创建以下三个构造函数: Matrix() ? 默认构造函数,应将矩阵初始化为无效状态。

显式矩阵(无符号整数 N)?应该构造一个有效的 NxN 矩阵,初始化为单位矩阵。(explicit 关键字不在教学大纲中,但应在此处使用。)

矩阵(无符号整数 M,无符号整数 N)?应该构造一个有效的 MxN 矩阵,初始化为零矩阵。(所有元素都为零。)

〜矩阵()?Matrix 的析构函数应该删除任何动态分配的内存。

My class this far is as follows:

到目前为止,我的课程如下:

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

And the rest of my code:

我的其余代码:

    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;
}

Have I created the dynamic array and the constructors correctly? I am later in the exercise to create three different arrays using the three different constructors. How do I do this correclty? If i try something like this

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

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

or

或者

Matrix::Matrix(3,4)

i get the following error:

我收到以下错误:

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

?ving_6.exe 中 0x773c15de 处的未处理异常:0xC0000005:访问冲突读取位置 0xcccccccc0。

What am i doing wrong?

我究竟做错了什么?

采纳答案by molbdnilo

In your constructors, you're defining a local variable

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

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

which shadows your member variable of the same name, so the member is never initialised.

这会影响您的同名成员变量,因此该成员永远不会被初始化。

All you should need is to change it to

您只需要将其更改为

matrix = new double[N * N];

And it's very un-C++ to use this->for member access unless it's absolutely necessary for disambiguation (which is almost never)

this->除非绝对需要消除歧义(几乎从不),否则用于成员访问是非常非 C++ 的

回答by qPCR4vir

You will find more "C++" (and sometime the only way to initialize members):

你会发现更多的“C++”(有时也是初始化成员的唯一方法):

Matrix::Matrix(int M, int N):   rows    (M), 
                                columns (N), 
                                matrix  (new double[M * N]) 
{
    for(int i = 0; i < M; i++)
        for(int j = 0; j < N; j++)
            matrix[i * N + j] =  0;

}

Now try to understand this:

现在试着理解这一点:

Matrix::Matrix(       int N):   rows    (N), 
                                columns (N), 
                                matrix  (new double[N * N]) 
{
    for(int i = 0; i < N; i++)
        for(int j = 0; j < N; j++)
            matrix[i * N + j] =  (i==j);

}

If you use:

如果您使用:

class Matrix{
private:
    int rows;
    int columns;
    std::unique_ptr<double[]> matrix;

you will find that you dont need a destructor, and some other inerest thing. Also, read my other answer.

你会发现你不需要析构函数和其他一些无关紧要的东西。另外,请阅读我的另一个答案。

回答by neutrino

In your three constructors, you are masking the instance variable matrix with a local one. Try this:

在您的三个构造函数中,您使用本地矩阵掩蔽实例变量矩阵。尝试这个:

Matrix::Matrix(){
 this->matrix = NULL;
}

Matrix::Matrix(int N){
 this->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){
 this->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;
}

}

}