Static 变量的初始化
2011-01-25 11:41
162 查看
这是一个基础性的问题,写在这里只是为了加深自己的印象。在类中所有的static变量必须在类定义的时候进行初始化,不能在内联函数(比如说构造函数)中初始化。
#include <iostream> using namespace std; class staticDemo { static int x; static int y; public: void print() const { cout << "x: " << x << endl << "y: " << y << endl; } }; int staticDemo::x = 10; int staticDemo::y = 100; int main() { staticDemo sd; sd.print(); }在c++标准当中, const static整形数据必须在类定义内部进行初始化,我们知道这个特性在VC6当中没有得到支持, 所以达不到编译期常量的作用。
#include <iostream> using namespace std; class values { // vc6.0当中,不支持类内部对static const int初始化, // 但是我们可以放到类定义的外部初始化,编译常量性失效 static const int x; static const float y; static const int a[5]; public: void print() const { cout << "x: " << x << endl << "y: " << y << endl; cout << "array is: " << endl; for(int i = 0; i < 5 an style="color: rgb(0, 0, 204);">; i++) { cout << a[i] << endl; } } }; const int values::x = 10; const float values::y = 3.1415; const int values::a[] = { 10, 20, 30, 40, 50 }; int main() { values vs; vs.print(); }总之引用作者的一句话来说:
// arrays, non-intergal and non-const static // must initialized externally |
相关文章推荐
- 类加载器在加载类 的时候就已经对类的static代码块和static变量进行了初始化
- static变量的初始化和赋值的区别
- Java static变量初始化顺序引发的bug
- String、StringBuffer、StringBuilder区别,HashMap与HashTable区别,final关键字详解及初始化成员变量位置,static关键字详解,抽象类与接口区别
- 静态(static)变量的初始化
- vc++对类内const static int变量初始化后的处理
- C++——Static变量初始化
- 关于全局、static对象/变量的初始化问题
- C++ static、const和static const类型成员变量声明以及初始化
- static成员变量定义初始化
- Java中的static使用之静态变量、静态方法和静态初始化块
- Static和Final修饰类属性变量及初始化
- Static和Final修饰类属性变量及初始化
- PHP的static变量初始化问题
- 只能被初始化一次的static变量???
- static变量初始化
- c++ 类与函数中static变量初始化问题(转)
- static关键字修饰变量的加载和初始化过程(Java)
- static成员必须在类外初始化,常量和变量的区别
- vc++对类内const static int变量初始化后的处理