考虑以下类:
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();
我不知道它为什么这样做,感觉它与整数指针“数据”和/或对象的创建方式有关,但我不确定是什么......任何和所有非常感谢帮助!非常感谢您。
更新:添加了析构函数
最佳答案
这两个代码语句都会产生未定义的行为。幸运的是,第一个有效,而第二个无效。
Stats statObject = Stats();
是拷贝初始化。它通过调用默认构造函数复制创建的 Stats
对象,然后通过调用复制构造函数将其复制到 statObject
中。请注意,您的类不提供复制构造函数,因此使用隐式生成的构造函数。这将创建动态分配成员的浅表拷贝。从中创建此拷贝的对象最终被销毁,然后您的类中剩下的是未指向任何有效内容的悬空指针。拷贝构造函数需要进行深拷贝。
同样的情况是:
Stats statObject;
statObject = Stats();
其中编译器生成的复制赋值运算符被调用。导致与案例1类似的问题。
您需要关注 Rule of Three 并为该类提供复制构造函数和复制赋值运算符。
关于c++ - 我的统计类打印垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15998300/