static counter in c++

前端 未结 5 1782
太阳男子
太阳男子 2020-12-31 11:25

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

I want the 1st object\'s ID to be 1, the 2nd to be 2, etc. I must use a st

5条回答
  •  既然无缘
    2020-12-31 11:45

    This:

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

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

提交回复
热议问题