C++填充动态数组int

问题描述:

我正在编写使用线程乘法矩阵的程序。我有填充动态int数组(不能使用向量)问题。C++填充动态数组int

CPP文件:HPP文件的

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

部分:

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

从调试,我得到:

这0x0079f7b0 {N_ = 3 M_ = 2 MAC_ = 00000000 { }}

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

+0

“Using 1st ..”创建一个临时对象,而不是预期对象的分配 – Jonas

+0

您可以使用委托构造函数 – Jonas

+0

@Jonas他不能使用委托构造函数,因为他首先必须使用'istream'争取获得施工参数。好的旧''init'函数在这里更适合 – wasthishelpful

// ... 

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

注:这里我拿出inititialization在功能init(也许应该是一个私有方法),以避免重复代码。