1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
Any data member of a class can be declared tt(static); be it in the tt(public)
or tt(private) section of the class interface. Such a data member is created
and initialized only once, in contrast to non-static data members which are
created again and again for each object of the class.
hi(static: data members) Static data members are created as soon as the
program starts. Even though they're created at the very beginning of a
program's execution cycle they are nevertheless true members of their classes.
It is suggested to prefix the names of static member with tt(s_) so they may
easily be distinguished (in class member functions) from the class's data
members (which should preferably start with tt(d_)).
Public static data members are hi(global variable)global variables. They may
be accessed by em(all of the program's code), simply by using their class
names, the scope resolution operator and their member names. Example:
verb( class Test
{
static int s_private_int;
public:
static int s_public_int;
};
int main()
{
Test::s_public_int = 145; // OK
Test::s_private_int = 12; // wrong, don't touch
// the private parts
})
The example does not present an executable program. It merely illustrates
the em(interface), and not the em(implementation) of tt(static) data members,
which is discussed next.
|