考虑以下类:
class Stats
{
private:
int arraySize; // size of array
int * data; // pointer to data, an array of integers
// default size of array in default constructor
static const int DEFAULT_SIZE = 10;
public:
Stats() // default constructor
{
arraySize = DEFAULT_SIZE; // element count set to 10
data = new int[DEFAULT_SIZE]; // array of integers
srand((unsigned int) time(NULL)); // seeds rand() function
// initializes integer array data with random values
for (int i = 0; i < DEFAULT_SIZE; i++)
{
// data filled with value between 0 and 10
data[i] = rand() % (DEFAULT_SIZE + 1);
}
}
~Stats() // destructor that deletes data memory allocation
{
delete [] data;
}
void displaySampleSet(int numbersPerLine)
{
cout << "Array contents:" << endl; // user legibility
// iterates through array and prints values in array data
for (int i = 0; i < arraySize; i++)
{
cout << data[i];
/* nested if statements that either prints a comma between
values or skips to next line depending on value of numbersPerLine */
if (i + 1 < arraySize)
{
if ((i + 1) % numbersPerLine != 0)
cout << ", ";
else
cout << endl;
}
}
}
}
出于某种原因,当我通过以下方式创建 Stats 对象时:
Stats statObject = Stats();
然后调用 displaySampleSet() ,数字显示正常。但是,当按以下方式创建 Stats 对象时,该函数会打印垃圾:
Stats statObject;
statObject = Stats();
我不知道它为什么这样做,并且感觉它与整数指针“数据”和/或创建对象的方式有关,但我不确定是什么......任何和所有的帮助都是完全的赞赏!非常感谢你。
更新:添加了析构函数