Effective C++(替换define)

编译器vs预处理器

  1. define为预处理器命令。
  2. 所以应该尽量少用预处理器命令。

define带来的问题

#define ASPECT_RATIO 1.653
const double AspectRatio = 1.653;
  1. 符号表问题

    • 问题:编译器看不见define的名字。所以报告错误让人困惑。define的名字,没有进入symbol
      table
    • 解决:使用const代替define
  2. 多份问题。

    预处理器盲目替换,可能导致多分define变量拷贝。const则不存在只会有一份副本。

char pointer based vs string

const char * const authorName = "Scott Meyers"; 
const std::string authorName("Scott Meyers");   // 比const char *const 更好

class 的成员

class GamePlayer { 
private:
    static const int NumTurns = 5; // 确保一个类只有一个副本,那么只能为static。这是一个声明不是定义。新编译器支持这样的语法,在声明的时候赋初值。
    int scores[NumTurns];
};

const int GamePlayer::NumTurns;    // 这是定义式

可能旧的编译器是不支持这样的。

class CostEstimate {
private:
    static const double FudgeFactor; // 生命
};

// 在另外的文件中定义
const double CostEstimate::FudgeFactor = 1.35;

enum hack

注意我们还是可以取地址访问到FudgeFactor.如何隐藏它呢?

class GamePlayer {
private:
    enum { NumTurns = 5 };
    int scores[NumTurns];
};

define and inline

// call f with the maximum of a and b
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))

注意使用define的话,全部要用小括号包起来。即便如此也会有问题

inta=5,b=0;
CALL_WITH_MAX(++a, b); // a is incremented twice
CALL_WITH_MAX(++a, b+10); // a is incremented once

inline 函数的好处

template<typename T>
inline void callWithMax(const T& a, const T& b) {
    f(a>b?a:b);
}

inline是正真的函数,有参数检查。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值