C++ C++;填充动态数组int

C++ C++;填充动态数组int,c++,constructor,dynamic-arrays,C++,Constructor,Dynamic Arrays,我正在写一个程序,它将使用线程乘以矩阵。我在填充动态整数数组时遇到问题(无法使用向量) 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

我正在写一个程序,它将使用线程乘以矩阵。我在填充动态整数数组时遇到问题(无法使用向量)

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_;
从调试中,我得到:

此0x0079f7b0{n_u=3 m_=2 mac_=0x00000000{???}

我知道我可以写
mac=newint(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\uu
未初始化,因此您的错误就出现了

按如下方式修改代码:

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
中进行初始化(应该是私有方法),以避免代码重复

看起来您认为在这里调用构造函数可以构造实际对象(
this
),然后访问其成员属性
mac

事实上,像您那样调用构造函数会创建一个与此矩阵无关的其他对象(因为您没有将其存储在变量中,所以它在行尾被销毁)

因此,由于您构建了另一个对象而不是
this
this->mac\uu
未初始化,因此您的错误就出现了

按如下方式修改代码:

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
中进行初始化(可能是一个私有方法)以避免代码重复。

“使用第一个..”创建一个临时对象,而不是为您可以使用的预期对象分配constructors@Jonas他不能使用委托构造函数,因为他首先必须使用给定的
istream
作为参数来获得结构参数。好旧的
init
函数在这里更好suited@wasthishelpful我的观点是正确的。在你进一步讨论之前,请确保
Matrix
遵守三个原则,否则不久你就会带着一个新问题回到这里。“Using 1st..”创建一个临时对象,而不是您可以使用的预期对象的分配constructors@Jonas他不能使用委托构造函数,因为他首先必须使用作为参数给出的
istream
,以获取构造参数。好旧的
init
函数在这里更好suited@wasthishelpful我的观点是正确的。在你进一步讨论之前,请确保
Matrix
遵守三个原则,否则不久你就会带着一个新问题回到这里。