C++ effective 阅读笔记

1:尽量用编译器而不用预处理(尽量用const 和 inline 而不用#define)

instance1:

#define DRV_L3_U32BIT_OFFSET (5)

可以用 const uchar DRV_L3_U32BIT_OFFSET = 5 替换。#define 的不存在于符号表中。

#define DRV_DEVM_L2MC_NAME   “L2MC” 

可以用 const char * const DRV_DEVM_L2MC_NAME = “L2MC” 替换

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

class GamePlayer

{

private:

  static const int NUM_TRUNS = 5;           //constant eclaration

  int scores[NUM_TRUNS];

  ...

};

上面的语句是NUM_TRUNS的声明,而不是定义,需要在类的实现代码中定义类的静态成员变量。

const int  GamePlayer::NUM_TRUNS;     //  mandatory definition(强制)  //goes in class impl.file

旧一点的编译器会不接受这种语法,认为类的静态成员在声明的时候定义初始值是非法的;而且类内只允许初始化整形,还只能是常量。

解决方法:

class EngineeringConstants       //goes in the class header file

{

private:

  static const double FUDGE_FACTOR;

  ...

};

//goes in the class implements file

const double EngineeringConstants ::  FUDGE_FACTOR = 1.35;

当类在编译的时候需要用到这个类的常量的情况,如GamePlayer ::scores 数组的声明,编译过程中编译器一定要知道数组的大小。

解决方案:借用enum方式来解决。需要int类型可以使用枚举的原则。

class GamePlayer

{

private:

  enum {NUM_TRUNS = 5}           //constant eclaration

  int scores[NUM_TRUNS];

  ...

};

instance2:

#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)     //因为不知道T的类型返回时传递引用可以提高效率

{

  return a > b ? a :b;

}

猜你喜欢

转载自www.cnblogs.com/starksqi/p/8856024.html