// ...
Matrix(n_, m_); // using 1st constructor
while (is.peek() != EOF) {
is >> tmp;
mac_[i] = tmp; // debug stop here
i++;
}
看起来您认为在这里调用构造函数构造了实际的对象(
this
),然后访问其成员属性
mac_
.
事实上,像这样调用构造函数会创建一个与此矩阵无关的其他对象(因为您没有将其存储在变量中,所以它会在行尾被销毁)。
因为你构建了另一个对象,而不是
这
,
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
(可能是私有方法)以避免代码重复。