static counter in c++

前端 未结 5 1762
太阳男子
太阳男子 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:30

    If the ID is static, then it will have the same value for all class instances.

    If you want each instance to have sequential id values, then you could combine the static attribute with a class variable, like this:

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

    If the application will be multi threaded, then you'll have to synchronize it with something like a pthread mutex.

提交回复
热议问题