|
||||
|
Section 10:
|
[10.13] Can I add = initializer; to the declaration of a class-scope static const data member?
Yes, though with some important caveats. Before going through the caveats, here is a simple example that is allowed:
// Fred.h
class Fred {
public:
static const int maximum = 42;
...
};
And, as with other static data
members, it must be defined in exactly one compilation unit, though this
time without the = initializer part:
// Fred.cpp #include "Fred.h" const int Fred::maximum; ...The caveats are that you may do this only with integral or enumeration types, and that the initializer expression must be an expression that can be evaluated at compile-time: it must only contain other constants, possibly combined with built-in operators. For example, 3*4 is a compile-time constant expression, as is a*b provided a and b are compile-time constants. After the declaration above, Fred::maximum is also a compile-time constant: it can be used in other compile-time constant expressions. If you ever take the address of Fred::maximum, such as passing it by reference or explicitly saying &Fred::maximum, the compiler will make sure it has a unique address. If not, Fred::maximum won't even take up space in your process's static data area. |
|||