现在的位置: 首页 > 综合 > 正文

effect c++ 1 const and enum

2014年02月22日 ⁄ 综合 ⁄ 共 1667字 ⁄ 字号 评论关闭

#define ASPECT_RATIO 1.653 
没有被加入
symbol table(符号表)。

解决方案是用 constant(常量)来取代 macro(宏):

const double AspectRatio = 1.653;   // uppercase names are usually for
                                    // macros, hence the name change

 

const char *
const authorName = "Scott Meyers";

更好的 authorName 的定义方式如下:

const std::string authorName("Scott Meyers");

 

 

将一个 constant(常量)的作用范围限制在一个 class(类)内,

class GamePlayer {

private:

static const int NumTurns = 5;      // constant declaration   NumTurns 的
declaration(声明),而不是 definition(定义)。

  int scores[NumTurns];               // use of constant
  ...
};

你可以提供如下这样一个独立的 definition(定义):
const int GamePlayer::NumTurns;     // definition of NumTurns; see

你应该把它放在一个 implementation file(实现文件)而非 header file(头文件)中。因为 class constants(类属常量)的 initial value(初始值)在声明时已经提供

 

 

一个 enumerated type(枚举类型)的值可以用在一个需要 ints 的地方。所以 GamePlayer 可以被如下定义:

class GamePlayer {

private:

enum { NumTurns = 5 };             // "the enum hack" - makes
                                     // NumTurns a symbolic name for 5

  int scores[NumTurns];              // fine
  ...
};

 

 

// call f with the maximum of a and b

#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))

这样的 macro(宏)有数不清的缺点,想起来就让人头疼。

无论何时,你写这样一个 macro(宏),都必须记住为 macro body(宏体)中所有的 arguments(参数)加上括号。否则,当其他人在表达式中调用了你的 macro(宏),你将陷入麻烦。但是,即使你确实做到了这一点,你还是会看到意想不到的事情发生:

int a = 5, b = 0;

CALL_WITH_MAX(++a, b);               // a is incremented twice

CALL_WITH_MAX(++a, b+10);            // a is incremented once

幸运的是,你并不是必须要和这样不知所云的东西打交道。你可以通过一个 inline function(内联函数)的 template(模板)来获得 macro(宏)的效率,以及完全可预测的行为和常规函数的类型安全(参见

Item 30
):

template<typename T>                               // because we don't

inline void callWithMax(const T& a, const T& b)    // know what T is, we

{                                                  // pass by reference-to-

  f(a > b ? a : b);                                // const - see
Item 20

}

 

 

抱歉!评论已关闭.