class X
{
static int serialno;
public:
static void setSerialno(int n);
X(void);
};
int X::serialno = 0;
void X::setSerialno(int n)
{
X::serialno = n;
}
X::X(void)
{
serialno++;
cout << "the constructor has been invoked " << serialno << " times." << endl;
}
In this example, the method X::setSerialno is also static,
and it does not belong to any specific object. If a programs needs to
reset the serial number, it can invoke this method as follows:
X::setSerialno(20);
In other words, instead of using an object to specify the context, a
class is used to specify the context. In C++, when a class is used to
specify the context (of a data member of method), the symbol
:: is used instead of ``'.'. Note that a class, not an
object, must supply the context of a static method/data member.
It also follows that a static method cannot access any
``regular'' (object owned) data member and methods.