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

静态常量变量 static const 变量,允许在一个类体中定义一个常量值,也可以
创建静态对象数组,包括const数组与非const数组\

//: C10:StaticArray.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Initializing static arrays in classes
class Values {
  // static consts are initialized in-place:
  static const int scSize = 100;
  static const long scLong = 100;
  // Automatic counting works with static arrays.
  // Arrays, Non-integral and non-const statics 
  // must be initialized externally:
  static const int scInts[];
  static const long scLongs[];
  static const float scTable[];
  static const char scLetters[];
  static int size;
  static const float scFloat;
  static float table[];
  static char letters[];
};

int Values::size = 100;
const float Values::scFloat = 1.1;

const int Values::scInts[] = {
  99, 47, 33, 11, 7
};

const long Values::scLongs[] = {
  99, 47, 33, 11, 7
};

const float Values::scTable[] = {
  1.1, 2.2, 3.3, 4.4
};

const char Values::scLetters[] = {
  'a', 'b', 'c', 'd', 'e',
  'f', 'g', 'h', 'i', 'j'
};

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'
};

int main() { Values v; } ///:~

利用全部类型的静态常量,可以在类内提供这些定义,但是对于其他的对象,
包括全部类型的数组,甚至它们为静态常量,必须为这些成员提供专门的
外部定义

无输出

也可以创建类的静态常量对象和这样的对象的数组
不过,不能使用“内联语法”初始化它们,这种语法对全部内建类型的静态常量
有效

//: C10:StaticObjectArrays.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Static arrays of class objects
class X {
  int i;
public:
  X(int ii) : i(ii) {}
};

class Stat {
  // This doesn't work, although 
  // you might want it to:
//!  static const X x(100);
  // Both const and non-const static class 
  // objects must be initialized externally:
  static X x2;
  static X xTable2[];
  static const X x3;
  static const X xTable3[];
};

X Stat::x2(100);

X Stat::xTable2[] = {
  X(1), X(2), X(3), X(4)
};

const X Stat::x3(100);

const X Stat::xTable3[] = {
  X(1), X(2), X(3), X(4)
};

int main() { Stat v; } ///:~

类对象的常量和非常量静态数组的初始化必须以相同的方式执行,它们遵守
典型的静态定义语法

无输出

猜你喜欢

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