我正在从infile中读取整数,然后使用指针将它们添加到int数组中。
我已经多次遍历代码,并且一切似乎都在逻辑上流动,并且在编译器中未收到任何语法错误或警告,因此我不确定出什么问题。
该程序要求我们使用数组而不是向量,否则我认为我不会遇到这些问题。
现在我的输出正在读取各种螺丝钉。我知道这与指针有关,但目前我很茫然。
文件内:
3
456
593
94
58
8
5693
211
输出:
The items in the array are as follows.
7476376, 7475472, -17891602, 17891602, -17891602, -17891602, -17891602, -178916
collections.h
class collections
{
public:
collections();
void add(int); //adds the value to the array.
void print(); //prints item of the array comma separated.
~collections();
protected:
int arraySize;
int *array;
};
构造函数:
collections::collections()
{
arraySize = 1;
array = new int[arraySize];
}//done
无效添加:
void collections::add(int value) //adds the value to the array.
{
//initial add to master array.
if (arraySize == 1)
{
array[0] = value;
arraySize++;
}
//every other add to master array.
else
{
//temp array.
int *tempArray = new int[(arraySize)];
//copies old array into temp array.
for (int i = 0; i < arraySize-1; i++)
{
tempArray[i] = array[i];
}
//adds new incoming value to temp array.
tempArray[(arraySize-1)] = value;
//new master array
delete [] array;
int *array = new int[arraySize];
//copies temp to master array.
for (int j =0; j < arraySize; j++)
{
array[j] = tempArray[j];
}
//cleanup
delete [] tempArray;
arraySize ++;
}
} //done
无效打印:
void collections::print() //prints item of the array comma separated.
{
cout << "The items in the array are as follows.\n";
for (int i = 0; i < arraySize; i++)
{
cout << array[i] << ", ";
}
}//done
抱歉,我知道这可能很简单,但是对于我一生来说,我看不到问题所在。
您不小心声明了其本地副本array
覆盖了类成员:
//new master array
delete [] array;
int *array = new int[arraySize];
^^^^^
int *
从最后一行删除,其余的看起来还可以。
PS:您考虑过使用std::vector<int>
吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句