Re: Static member in a class
* Victor Bazarov:
stonny wrote:
I read the following sentence from a c++ website, but can not
understand why. can anyone help me with it?
"
An important detail to keep in mind when debugging or implementing a
program using a static class member is that you cannot initialize the
static class member inside of the class. In fact, if you decide to put
your code in a header file, you cannot even initialize the static
variable inside of the header file; do it in a .cpp file instead.
"
The Standard requires that every static data member is defined at the
namespace level. In order to comply with the One Definition rule, you
are more likely to succeed if you place the definition of the static
data member in a .cpp file (instead of a header which can be included
in more than one translation unit). Initialisation accompanies the
definition. That's why you should initialise static data members in
a .cpp file (and only in one .cpp file).
Initialization accompanies definition of a constant except in the case
when a declaration of a static constant in a class supplies the
initializer, in which case the definition (if any, and then outside the
class) is sans initializer.
Example:
struct S
{
static int const x = 42; // Not a definition, per ?9.4.2/2.
};
If the address of S::x is used, or in the standard's terminology, if
S::x is "used", a definition is formally (but with current compilers not
necessarily in practice) required, outside the class:
int const S::x; // A definition, per ?9.4.2/4.
Not directed at you, but at other readers: this construct is only
supported for integral types and/including enum types.
Directed at whoever thought up this crazy scheme: ugh.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?