Bruce Eckel's Thinking in C++, 2nd Ed | Contents | Prev | Next |
class A { static int i; public: //...
//: C10:Statinit.cpp // Scope of static initializer #include <iostream> using namespace std; int x = 100; class WithStatic { static int x; static int y; public: void print() const { cout << "WithStatic::x = " << x << endl; cout << "WithStatic::y = " << y << endl; } }; int WithStatic::x = 1; int WithStatic::y = x + 1; // WithStatic::x NOT ::x int main() { WithStatic ws; ws.print();
//: C10:StaticArray.cpp // Initializing static arrays class Values { // static consts can be initialized in-place: static const int scSize = 100; // Automatic counting works with static consts: static const float scTable[] = { 1.1, 2.2, 3.3, 4.4 }; static const char scLetters[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' }; // Non-const statics must be // initialized externally: static int size; static float table[4]; static char letters[10]; }; int Values::size = 100; float Values::table[4] = { 1.1, 2.2, 3.3, 4.4 }; char Values::letters[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
//: C10:Local.cpp // Static members & local classes #include <iostream> using namespace std; // Nested class CAN have static data members: class Outer { class Inner { static int i; // OK }; }; int Outer::Inner::i = 47; // Local class cannot have static data members: void f() { class Local { public: //! static int i; // Error // (How would you define i?) } x; }
class X { public: static void f(); };
//: C10:StaticMemberFunctions.cpp class X { int i; static int j; public: X(int ii = 0) : i(ii) { // Non-static member function can access // static member function or data: j = i; } int val() const { return i; } static int incr() { //! i++; // Error: static member function // cannot access non-static member data return ++j; } static int f() { //! val(); // Error: static member function // cannot access non-static member function return incr(); // OK -- calls static } }; int X::j = 0; int main() { X x; X* xp = &x; x.f(); xp->f(); X::f(); // Only works with static members
//: C10:Selfmem.cpp // Static member of same type // ensures only one object of this type exists. // Also referred to as a "singleton" pattern. #include <iostream> using namespace std; class Egg { static Egg e; int i; Egg(int ii) : i(ii) {} public: static Egg* instance() { return &e; } int val() { return i; } }; Egg Egg::e(47); int main() { //! Egg x(1); // Error -- can't create an Egg // You can access the single instance: cout << Egg::instance()->val() << endl;