类实例的唯一ID [英] Unique id of class instance

查看:103
本文介绍了类实例的唯一ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的班级:

class ExampleClass {

private:
    int _id;
    string _data;

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

    }
    //and so on...    

}

如何在不使用全局变量的情况下为类的每个实例添加唯一的(!)整数标识符(_id)?

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

推荐答案

使用私有静态成员int,在类的所有实例之间共享。
在构造函数中的static int中,只需将其递增,然后将其值保存到您的id成员;

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;
    }

更新:

您将需要在复制构造函数和operator =中考虑所需的行为(取决于您的需求,一个新对象或相同对象)。

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).

这篇关于类实例的唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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