设为首页 加入收藏

TOP

Item 2: Prefer consts, enums, and inlines to #defines.(3)
2013-10-07 14:25:31 来源: 作者: 【 】 浏览:53
Tags:Item Prefer consts enums and inlines #defines.

Note, by the way, that there’s no way to create a class-specific constant using a #define, because #defines don’t respect scope. Once a macro is defined, it’s in force for the rest of the compilation (unless it’s #undefed somewhere along the line). Which means that not only can’t #defines be used for class-specific constants, they also can’t be used to provide any kind of encapsulation, i.e., there is no such thing as a “private” #define. Of course, const data members can be encapsulated; NumTurns is.

Older compilers may not accept the syntax above, because it used to be illegal to provide an initial value for a static class member at its point of declaration. Furthermore, in-class initialization is allowed only for integral types and only for constants. In cases where the above syntax can’t be used, you put the initial value at the point of definition:

  1. class CostEstimate {  
  2. private:  
  3.   static const double FudgeFactor; // declaration of static class  
  4.   ...  // constant; goes in header file  
  5. };  
  6. const double  // definition of static class  
  7.   CostEstimate::FudgeFactor = 1.35;  // constant; goes in impl. file 

This is all you need almost all the time. The only exception is when you need the value of a class constant during compilation of the class, such as in the declaration of the array GamePlayer::scores above (where compilers insist on knowing the size of the array during compilation). Then the accepted way to compensate for compilers that (incorrectly) forbid the in-class specification of initial values for static integral class constants is to use what is affectionately (and non-pejoratively) known as “the enum hack.” This technique takes advantage of the fact that the values of an enumerated type can be used where ints are expected, so GamePlayer could just as well be defined like this:

  1. class GamePlayer {  
  2. private:  
  3.   enum { NumTurns = 5 };  // “the enum hack” — makes  
  4.  // NumTurns a symbolic name for 5  
  5.   int scores[NumTurns];  // fine  
  6.   ...  
  7. }; 

关于enum { NumTurns = 5 };

早期的C++(www.cppentry.com)编译器无法识别数字常量,而C++(www.cppentry.com)也不支持用变量定义数组。为了避免宏的使用,使用 enum 是常见的方法。

关于int scores[Numturns];

纯粹的STL派可能更喜爱使用std::vector或boost::array。但不可否认,几乎没有人坚持完全不用build-in数组。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Item 2: Prefer consts, enums, a.. 下一篇Item 2: Prefer consts, enums, a..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: