c++ - 我的统计类打印垃圾

标签 c++ pointers

考虑以下类:

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/

相关文章:

c++ - std::vector 不支持右值赋值

c++ - 为什么 istream、ostream、iostream、ios_base 都在这里工作

c++ - 当前时间作为创建文件的字符串

c++ - 将对象地址转换为字符指针,然后对它们使用指针数学

pointers - 设置指针类型的结构域

c++指针问题 - 通过方法更新指针

c++ - 如何避免与 native NuGet 包发生重复的 DLL 冲突?

c++ - 尝试对 g++ 进行颜色编码

c++ - 减去指针 : Where does this missing level of indirection come from?

c 如何在修改后的树中保留数据