【原创】(学习笔记)静态常量成员变量的初始化

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

/*

主题:静态常量成员变量的初始化:

书名:<<The C++ Standard Library -A Tutorial and Reference>>

P25 (2.2.8 Initialization of Contants Static Members)

*******************************************************************

It is now possible to initialize integral constant static members inside the class structure.

This is useful when the constants is used in the class structure after the initialization.

(对于当这个常量会在初始化后要使用的情况,这样做会比较有效)

For example ===>

class MyClass{

static const int NUM = 100;

int elements[NUM];

...

};

Note that you still have to to define space for a constant static member that is initialized within a class definition:

const int MyClass::NUM; //no initialization here

*/

#pragma warning(disable:4530)

#include <iostream>

using namespace std;

class A

{

public:

A(){

for(int i=0; i<SIZE; i++)

num[i] = i;

}

void print(){

for(int i=0; i<SIZE; i++)

cout<<num[i]<<" "<<endl;

}

private:

static const SIZE = 10;

//注意:由于SIZE作为一个const常量,所以必须在首次定义的时候就给它赋值。

int num[SIZE];

};

const int A::SIZE;

//注意:由于SIZE作为一个类的静态成员,应该在类体外部定义(以取得和全局变量类似的效用)

int main()

{

A a;

a.print();

return 0;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有