静态成员(static members)(二)
Integral(int, long, char, short) const static Members Are Special
Ordinarily, class static members, like ordinary data members, cannot be initialized in the class body. Instead, static data members are normally initialized when they are defined.
One exception to this rule is that a const static data member of integral type can be initialized within the class body as long as the initializer is a constant expression:
class Account { public: static double rate() { return interestRate; } static void rate(double); // sets a new rate private: static const int period = 30; // interest posted every 30 days double daily_tbl[period]; // ok: period is constant expression };
A const static data member of integral type initialized with a constant value is a constant expression. As such, it can be used where a constant expression is required, such as to specify the dimension for the array member daily_tbl .
注意,别发生重复定义的错误
class Account { public: static double rate() { return interestRate; } static void rate(double); // sets a new rate private: static const int period = 30; // interest posted every 30 days double daily_tbl[period]; // ok: period is constant expression }; const Account::int period = 20; // 类内和类外各定义一次。错误
Because a static member is not part of any object, static member functions may not be declared as const . After all, declaring a member function as const is a promise not to modify the object of which the function is a member. Finally, static member functions may also not be declared as virtual.
#include<iostream> using namespace std; class Test { public: static int init() const {return 2;} }; int main() { cout << Test::init() << endl; } // error: static member function ‘static int Test::init()’ cannot have cv-qualifier(const and volatile)
Because static data members are not part of any object, they can be used in ways that would be illegal for nonstatic data members.
As an example, the type of a static data member can be the class type of which it is a member. A nonstatic data member is restricted to being declared as a pointer or a reference to an object of its class:
class Bar { public: // ... private: static Bar mem1; // ok Bar *mem2; // ok Bar mem3; // error };
Similarly, a static data member can be used as a default argument:
class Screen { public: // bkground refers to the static member // declared later in the class definition Screen& clear(char = bkground); private: static const char bkground = '#'; };
A nonstatic data member may not be used as a default argument because its value cannot be used independently of the object of which it is a part. Using a nonstatic data member as a default argument provides no object from which to obtain the member's value and so is an error.
浙公网安备 33010602011771号