C++编程思想 第1卷 第10章 名字控制 C++中的静态成员 定义静态数据成员的存储

因为类的静态数据成员有着单一的存储空间而不管产生了多少个对象,所以存储
空间必须在一个单独的地方定义

定义必须出现在类的外部 不允许内联 而且只能定义一次,因此它突出放在一个
类的实现文件中

静态成员的初始化表达式是在一个类的作用域内

//: C10:Statinit.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// 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();
  getchar();
} ///:~

这里,withStatic::限定符把withStatic的作用域扩展到全部定义中

输出
WithStatic::x = 1
WithStatic::y = 2

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81178436