Effective C++ Item 2 尽量以const, enum, inline 替换 #define

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


尽量以const, enum,inline 替换 #define --》 宁可以编译器替换预处理器

1.对于单纯常量,最好以const 对象或enum替换#define

         不要用

         #define ASPECT_RATIO 1.653


         而用

         const double AspectRatio = 1.653

         两点注意

         1.指向常量char *的字符串的常量指针

         const char * const authorName = “Scott Meyers”

         第一个const 表示指针指向的内容是不变的;第二个const表示指针本身的值是不变的

         2.class专属常量

#include <iostream>
using namespacestd;
 
class A{
private:
    static const int num = 5; //声明
    int score[num];
};
 
const intA::num; //定义
 
int main(){
    //constint A::num; //error: member A::num cannot be define in the current scope
    system("pause");
}


 

2. 对于形似函数的宏(macro),最好改用inline函数替换#define

         不要用

//以a和b的较大值调用f函数
#define CALL_WITH_MAX(a,b) f((a) > (b) ? (a) : (b))
int a = 5, b =0;
CALL_WITH_MAX(++a,b);   // a被累加二次
CALL_WITH_MAX(++a,b+10);// a被累加一次


 

         而用

template<typenameT>
inline void callWithMax(const T &a, const T &b)
 //由于不知道T是什么类型,所以采用pass by reference-to-const
{
    f(a > b ? a : b);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值