简体   繁体   中英

Iterate a variable within a class each time a new object is created

Hello all I'm trying to have a class iterate a variable each time I instantiate the class again.
For example:
I have the header file as follows

class IterateTest{

public:
//Default Constructor
IterateTest();

private:
    int m_ID; //Specific ID
};

Say I am creating instances is this way:

vector<IterateTest*> iterations;
for ( int i = 0; i < 10; i++ )
  iterations.push_back( new IterateTest() );

I want to end up having the ID for each IterateTest increment by 1 when the new one is created. ending up with the IDs in my vector being 1, 2, 3, 4, etc...
I'm not sure how to accomplish this. I cannot change the way in which I'm building the vector I just have to handle this from within the IterateTest class.

I don't really know where to start for this one and thus haven't tried many methods thus far. I've been googling for a while now and I can't find a solution whether I just don't know what to google to fid it or it's not out there I don't know..

Thanks guys for your help!

Since static variables are shared across all instances of the class, you can create a static variable that is incremented in the constructor:

class A
{
private:
    int _id;
    static int CurrentID;

public:
    A() : _id( ++CurrentID ) {}

    int getID() const { return _id; }
};

int A::CurrentID = 0;

int main() {

    std::vector<A*> vec;
    for( int i = 0; i < 5; ++i )
        vec.push_back( new A() );

    for( auto a : vec )
        std::cout << a->getID() << std::endl;

    return 0;
}

There are a couple of things to note:

  • Each time the program is run, the ID will start at 1 again
  • This is not thread-safe

How about fixing the IterateTest to

class IterateTest{

public:
//Default Constructor
IterateTest(int id): m_ID(id) {};

private:
    int m_ID; //Specific ID
};

and then write

vector<IterateTest*> iterations;
for ( int i = 0; i < 10; i++ )
  iterations.push_back( new IterateTest(i+1) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM