Assuming you are talking about a static data member, since a static member of a function is not a problem, there are various methods for different cases:
Simple integral type const,, address not accepted:
Give it a value in the declaration in the class definition. Or you can use a type enum.
Another type, logically persistent:
Use C ++ 11 constexpr.
, constexpr:
Meyers.
:
class Foo
{
private:
static
auto n_instances()
-> int&
{
static int the_value;
return the_value;
}
public:
~Foo() { --n_instances(); }
Foo() { ++n_instances(); }
Foo( Foo const& ) { ++n_instances(); }
};
:
template< class Dummy >
struct Foo_statics
{
static int n_instances;
};
template< class Dummy >
int Foo_statics<Dummy>::n_instances;
class Foo
: private Foo_statics<void>
{
public:
~Foo() { --n_instances; }
Foo() { ++n_instances; }
Foo( Foo const& ) { ++n_instances; }
};
: .