您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: