C ++中的静态计数器 [英] static counter in c++

查看:108
本文介绍了C ++中的静态计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 Data 类,该类的每个对象均具有唯一的ID。

I'm trying to create a Data class whose objects each hold a unique ID.

我想要第一个对象的ID为1,第二个对象的ID为2,依此类推。我必须使用 static int ,但是 all 对象具有相同的ID,而不是1、2、3 ...

I want the 1st object's ID to be 1, the 2nd to be 2, etc. I must use a static int, but all the objects have the same ID, not 1, 2, 3...

这是 Data 类:

class Data
{
private:
   static int ID;
public:
   Data(){
   ID++;
   }
};

我该怎么做,所以第一个ID为1,第二个ID为2,依此类推..?

How can I do it so the first one ID would be 1, the second would be 2, etc..?

推荐答案

此:

class Data
{
private:
   static int ID;
   const int currentID;
public:
   Data() : currentID(ID++){
   }
};

除了静态计数器,您还需要实例绑定成员。

Besides a static counter, you also need an instance-bound member.

这篇关于C ++中的静态计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆