Const 小解

参考《Effective C++, Item 1》

对于文中所述,

 

定义某个类(class)的常量一般也很方便,只有一点点不同。要把常量限制在类中,首先要使它成为类的成员;为了保证常量最多只有一份拷贝,还要把它定义为静态成员:

class GamePlayer {

private:

static const int NUM_TURNS = 5; // constant declaration

int scores[NUM_TURNS]; // use of constant

...

};

 

还有一点,正如你看到的,上面的语句是NUM_TURNS 的声明,而不是定义,所以你还必须在类的实现代码文件中定义类的静态成员:

const int GamePlayer::NUM_TURNS; // mandatory definition;

// goes in class impl. file

 

 

在VC6.0里面编译,错误如下

d:\program files\microsoft visual studio\myprojects\const\const.cpp(8) : error C2258: illegal pure syntax, must be '= 0'
d:\program files\microsoft visual studio\myprojects\const\const.cpp(8) : error C2252: 'NUM_TURNS' : pure specifier can only be specified for functions 
d:\program files\microsoft visual studio\myprojects\
const\const.cpp(9) : error C2065: 'NUM_TURNS' : undeclared identifier
d:\program files\microsoft visual studio\myprojects\
const\const.cpp(9) : error C2057: expected constant expression d:\program files\microsoft visual studio\myprojects\const\const.cpp(9) :
warning C4200: nonstandard extension used : zero-sized array in struct/union

 

MSDN提示错误C2252如下:'identifier' : pure specifier can only be specified for functions

《C++编程思想》中说明:因为在类对象里进行了存储空间分配,编译器不能知道const的内容是什么,所以不能把它用做编译期间的常量。这意味着对于类里的常数表达式来说,const就像它在C中一样没有作用

 

如第一条提示,修改类PASS代码

class GamePlayer {

private:

static const int NUM_TURNS ; // constant declaration

//int scores[NUM_TURNS]; // use of constant

...

};

const int GamePlayer::NUM_TURNS; // mandatory definition;

// goes in class impl. File

        Const int GamePlayer::NUM_TURNS = 5;

 

《Effective C++, Item 1》方案为:

旧一点的编译器会不接受这种语法,因为它认为类的静态成员在声明时定义初始值是非法的;而且,类内只允许初始化整数类型(如:int, bool, char 等),还只能是常量。

在上面的语法不能使用的情况下,可以在定义时赋初值:

class EngineeringConstants { // this goes in the class

private: // header file

static const double FUDGE_FACTOR;

...

};

// this goes in the class implementation file

const double EngineeringConstants::FUDGE_FACTOR = 1.35;

对头,也就是说VC6.0编译器太旧,此方法可以编译通过。但是注释了数组声明语句才可以,就如上面所说,在类对象里进行了存储空间分配,编译器不能知道const的内容是什么,所以不能把它用做编译期间的常量。在编译阶段数组的size必须为常量,而此类里面不知道FUDGE_FACTOR的值是什么,所以也会报错

 

那么在旧一点的编译器里面的解决方法如下:《Effective C++, Item 1》提供

为了弥补那些(不正确地)禁止类内进行整型类常量初始化的编译器的不足,可以采用称之为“借用enum”的方法来解决。这种技术很好地利用了当需要int 类型时可以使用枚举类型的原则,所以,GamePlayer 也可以象这样来定义:

class GamePlayer {

private:

enum { NUM_TURNS = 5 }; // "the enum hack" — makes

// NUM_TURNS a symbolic name

// for 5

int scores[NUM_TURNS]; // fine

...

};

 

如此,O了,那么在新的编译器里面是怎么样的了?

装一VS2005,Ctrl + C,Ctrl +V

Perfect

+++++++++++++++++++++++++++++++++++++++++++++++Eric Xiang+++++++++++++++++++++++++++++++++++++++++++++++++++++

posted @ 2013-03-05 10:13  xh_green  阅读(242)  评论(0)    收藏  举报