Chinaunix首页 | 论坛 | 博客
  • 博客访问: 513122
  • 博文数量: 158
  • 博客积分: 4015
  • 博客等级: 上校
  • 技术积分: 1711
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-27 14:00
文章分类

全部博文(158)

文章存档

2010年(71)

2009年(87)

我的朋友

分类: C/C++

2010-01-28 01:56:23

这是一个基础性的问题,写在这里只是为了加深自己的印象。
在类中所有的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; 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



阅读(1318) | 评论(0) | 转发(0) |
0

上一篇:纯资源型的DLL

下一篇:嵌套类中的static

给主人留下些什么吧!~~