creating multiple objects automatically numbered

时间:2016-11-26 18:35:47

标签: c++

I've got a basic question. Is it possible to number objects automatically? So for example if I have a class 'item' and in the main I have

item item1(weight, length);
item item2(weight, length);

and in the constructor of the item class we assign the weight and length to the corresponding variables.

class item {

public:
item(int w, int l){
weight = w ;
length = l ;
itemnumber = ??? ;

private:
int weight;
int length;
int itemnumber;
};

But on top of that I also want a variable itemnumber. This itemnumber should be 1 the first time I create an object (so 1 for item1) and 2 the second object created (item2) and so on. But I don't want to pass it as a parameter. So basically what should I put instead of the '???' in my code ?

Is this possible?

2 个答案:

答案 0 :(得分:3)

Create a static field inside class, and increment it in constructor.

something like this:

class A {
public:
    A() : itemnumber(nextNum) { ++nextNum; }
private:
    int itemnumber;
    static int nextNum;
}

// in CPP file initialize it
int A::nextNum = 1;

Also, don't forget to increment static field in copy and move constructors\operators.

答案 1 :(得分:0)

使用静态变量,如

class rect{
public:
static int num;
rect(){num++;}
};

int rect::num =0;
int main(){
rect a();
cout << rect::num;
}