在C ++中,如何使用单例确保每个类都有唯一的整数ID? [英] in C++, how to use a singleton to ensure that each class has a unique integral ID?

查看:208
本文介绍了在C ++中,如何使用单例确保每个类都有唯一的整数ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆C ++类。

我想让每个类都有类似的:

I want each class to have something like:

static int unique_id;

同一个类的所有实例应该具有相同的unique_id;不同的类应该有不同的unique_id。

All instances of a same class should have the same unique_id; different classes should have different unique_id's.

最简单的做法似乎是通过类穿线单例。

The simplest way to do this appears to be threading a singleton through the classes.

但是,对于静态类成员/在main之前发生的事情,我不知道该调用什么。

However, I don't know what's called when for static class members / things that happen before main.

(1)如果你有一个解决方案

(1) if you have a solution that does not involve using singleton, that's fine too

(2)如果你有一个解决方案给我一个:

(2) if you have a solution that gives me a :

int unique_id(); 

很好。

推荐答案

有一个类在每次创建时增加它的ID。然后使用该类作为应该有ID的每个对象中的静态字段。

Have a class that increments it's ID on each creation. Then use that class as a static field in each object that is supposed to have an ID.

class ID
{
    int id;
public:
    ID() {
        static int counter = 0;
        id = counter++;
    }

    int get_id() {  return id; }
};

class MyClass
{
    static ID id;
public:
    static int get_id() 
    {
        return id.get_id();
    }
};

这篇关于在C ++中,如何使用单例确保每个类都有唯一的整数ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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