質問

My teacher required us to create ID data member that's generated automatically, and once established it can’t be modified. What is the most appropriate type? if the answer is static const int ID;

How can I generate it automatically while it's const?

役に立ちましたか?

解決

Since the ID has to be unique, one shall make sure, that two instances never get the same ID. Also, noone outside class should interfere in generating the UID.

First, you define a static field in your class:

class Data
{
private:
    static int newUID;

(...)
};

// The following shall be put in a .cpp file
int Data::newUID = 0;

Then, after each instance is created, it should take a new ID value and increment the newUID counter:

class Data
{
(...)
    const int uid;  

public:
    Data()
        : uid(newUID++)
    {
    }

    int GetUid()
    {
        return uid;
    }
};

Noone has access to internal newUID except the class, ID is generated automatically for each instance and you are (almost1) sure, that no two instances will have the same ID number.


1 Unless you generate a little more than 4 billion instances

他のヒント

Here is an example:

class SomeClass {
   static int currID;

public:
   const int ID;

   SomeClass() :
      ID(currID++) {  // Initialization list used to initialize ID

   }
};

And you must put this somewhere in your .cpp file:

int SomeClass::currId = 0;

This uses initialization lists to do the trick. We must do it this way for it is only in initialization lists where you can assign to a const member in an instance.

The core concept is that you must have a "global setting" to keep track of the ID that would be assigned to instances created in the future. It is currID in this example. For each instance created in your class, you assign the value of currID as the ID of that instance then increment it (currID). In this way, you get instances which have unique IDs.

create a const ID as int , initialize it in constructor initialization list like

 SomeClass(): id(++staticIncrementingInt){
   ///other stuf here
 }

Hope this helps.

You can actually call a function (rand, in this case) in the construction initialization list. Up to you now how you can seed it.

If your teacher allows boost libs then try Boost.Uuid. An example is here. It is RFC 4122 compliant.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top