0
If i want to know how many objects exist momently in species class(for example myclass) what should I do?
3 ответов
+ 2
You could create a static class member (static long int instances = 0;) The class constructor(s) would increment the member (instances) whenever an object is created. The class destructor would decrement the member (instances) each time it deleted an instance of the class. A getter function could then be used to obtain the value of the member (instances), which is the number of objects of the class currently in use.
If running in a threaded or parallel processing environment care should be taken to serialize accesses of the member (instances).
It looks like the member (instances) must be public.
+ 2
In the constructor just add a line with
++myClass::instances;
and in the destructor
--myClass::instances;
and the value may be obtained as
myClass::instances
Where myClass is the name of the class you are working with.
0
Tnx. But how can I write in a constructor to increment the member whenever an object is created?