创建动态数组时,会增加静态成员(计数器)
When creating dynamic array static member (counter) is increased
假设我正在编写一个项目目录,其中每个项目都有唯一的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
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 使用静态成员声明类时遇到问题
- C++:是否可以使用非静态成员变量模板?
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 如何在复杂继承中访问静态成员变量
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 静态成员变量不会由 gettext 转换
- decltype:使用指针访问类的静态成员
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 静态私有成员计数器
- 创建动态数组时,会增加静态成员(计数器)