Unique id of class instance

社会主义新天地 提交于 2019-12-11 06:30:08

问题


I have a class like this:

class ExampleClass {

private:
    int _id;
    string _data;

public:
    ExampleClass(const string &str) {
        _data = str;
    }
    ~ExampleClass() {

    }
    //and so on...    

}

How can I add unique(!) integer identifier (_id) for every instance of the class without using global variable?


回答1:


Use a private static member int, is shared among all instance of the class. In static int in the constructor just increment it, and save it's value to your id member;

class ExampleClass {

private:
    int _id;
    string _data;
    static int counter=0;
public:
    ExampleClass(const string &str) {
        _data = str;
         id=++counter;
    }

Update:

You will need to take consideration in your copy constructor and operator= what behavior you want (depends on your needs, a new object or an identical one).




回答2:


You can hide a static data in your class, which will provide the unique id.

Example:

class ExampleClass {

private:
    int _id;
    static int idProvider;
public:
    ExampleClass(const string &str) 
          : _id(++idProvider)
    {} 
}

int ExampleClass::idProvider = 0;

the logic is everytime you created an object of ExampleClass it will increment the idProvider which will then assign as a unique id to your id



来源:https://stackoverflow.com/questions/40444153/unique-id-of-class-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!