C 填充动态阵列int

C++ fill dynamic array int

本文关键字:int 阵列 动态 填充      更新时间:2023-10-16

我正在编写程序,该程序将使用线程乘坐矩阵。我有填充动态int array 的问题(无法使用vector)

CPP文件:

Matrix::Matrix(int n, int m)
{
    mac_ = new int[n * m];
}
Matrix::Matrix(std::istream & is)
{
    int tmp;
    int i = 0;  
    is >> m_; //rows
    is >> n_; //columns
    Matrix(n_, m_); // using 1st constructor
    while (is.peek() != EOF) {
        is >> tmp;
        mac_[i] = tmp; // debug stop here
        i++;
    }
}

HPP文件的一部分:

private:
    int n_; // columns
    int m_; // rows
    int *mac_;

从调试中我得到:

this 0x0079f7b0 {n_ = 3 m_ = 2 mac_ = 0x00000000 {???}}

我知道我可以在第二个构造函数中编写 mac_ = new int(n_*m_);,但我想知道为什么第一个不起作用。

// ...
Matrix(n_, m_); // using 1st constructor
while (is.peek() != EOF) {
    is >> tmp;
    mac_[i] = tmp; // debug stop here
    i++;
}

看起来您认为在此处调用构造函数构造实际对象(this),然后您访问其成员属性mac_

实际上,当您创建了与此矩阵无关的另一个对象时,请调用构造函数(由于您没有将其存储在变量中,因此在行末尾被破坏)。

因此,由于您构造了另一个对象而不是this,因此this->mac_是不可原始化的,因此您的错误。

这样修改您的代码:

Matrix::Matrix(int n, int m)
{
    init(n, m);
}
Matrix::Matrix(std::istream & is)
{
    int tmp;
    int i = 0;  
    is >> m_; //rows
    is >> n_; //columns
    init(n_, m_);
    while (is.peek() != EOF) {
        is >> tmp;
        mac_[i] = tmp; // debug should not stop here anymore
        i++;
    }
}
void Matrix::init(int n, int m)
{
    mac_ = new int[n * m];
}

注意:在这里,我在函数init中取出启动(可能是私人方法)以避免代码重复。