C 填充动态阵列int
C++ fill dynamic array int
我正在编写程序,该程序将使用线程乘坐矩阵。我有填充动态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
中取出启动(可能是私人方法)以避免代码重复。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- OpenMP阵列性能较差
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有从阵列<float>到阵列<int>的可行转换
- 如何将来自文本文件的数据读取到结构的int阵列中
- 在int阵列上尾随零
- CIN正在为char阵列工作,但不为int阵列工作
- 从指针打印动态int阵列中获取怪异的字符
- 将INT转换为具有选定格式的char阵列
- 将int阵列转换为c 中int的向量
- C 填充动态阵列int
- 将字符阵列转换为INT指针
- 我将如何将char阵列转换为int
- 将int阵列填充有位