千里之行,始于足下

《effective c++ II》学习笔记 Item1 Prefer const and inline to #define

宏定义
#define ASPECT_RATIO 1.653

主要是宏在预编译的时候被移除,不加入编译器编译,不利于错误的检测,给调试维护带来一定困难。
因而用
const double ASPECT_RATIO = 1.653;

代替。
存在2个小问题需要注意:
1)    指针常量问题
const char * const authorName = "Scott Meyers";

需要2次使用”const”
2)    在类的定义中
class GamePlayer {
private:
  
static const int NUM_TURNS = 5;    // constant declaration
  int scores[NUM_TURNS];             // use of constant
  
};

此外,还必须在.cpp文件中予以定义:
const int GamePlayer::NUM_TURNS;      // mandatory definition;
                                      
// goes in class impl. file


值得注意的是老的编译器不支持这种表达方式,因此要采用如下的方式:
 
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;


这种情形下如果要在类中定义常量数组,需要采用枚举类型做一折中处理:
class GamePlayer {
private:
  
enum { NUM_TURNS = 5 };    // "the enum hack" — makes
                             
// NUM_TURNS a symbolic name
                             
// for 5
  int scores[NUM_TURNS];     // fine

};


避免
#define max(a,b) ((a) > (b) ? (a) : (b))

这种写法。
采用内连函数:
inline int max(int a, int b) { return a > b ? a : b; }

增强适应性,应采用模板类:
template<class T>
inline 
const T& max(const T& a, const T& b)
return a > b ? a : b; }

总结:并不是说不使用宏,要明确地知道使用宏后可能会引起的后果,减少有歧义的情况发生。
 

posted on 2007-12-10 14:36 rednight 阅读(196) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理