创建动态数组时,会增加静态成员(计数器)

When creating dynamic array static member (counter) is increased

本文关键字:静态成员 计数器 增加 动态 数组 创建      更新时间:2023-10-16

假设我正在编写一个项目目录,其中每个项目都有唯一的id。该id由自动增加的计数器-静态变量确定,该变量初始化为零。我希望我的目录是一个动态数组。问题是,如果我创建一个大小为10的数组,即使在我创建并放置任何对象之前,我的静态计数器也会增加到10。为什么会这样,我该如何避免呢?

我的示例代码:

#include <stdlib.h>
#include <iostream>
using namespace std;
class Item
{
private:
    int id;
public:
    static int next_id;
    Item();
};
int Item::next_id = 0;
Item::Item()
{
    id = Item::next_id++;
}
int main()
{
    Item* catalogue;
    catalogue = new Item[10];
    cout << Item::next_id << endl;
    system("pause");
    return 0;
}

输出为:

10

正如您所看到的,我没有创建任何Item对象,但是next_id已经是10了。因此,如果我尝试创建一个Item对象,它的id将为11。

此处catalogue = new Item[10];new运算符将调用Item类的构造函数10次,因此Item::next_id = 10