zoukankan      html  css  js  c++  java
  • [Effective C++, 学习总结] 02 尽量以const, enum, inline替换#define

    #define ASPECT_RATIO            1.653
    // 替换
    const double AspectRatio = 1.653

    若要在头文件内定义一个常量,如下示例:

    const char * const authorName = "Scott Meyers";

     class专属常量

    1 class GamePlayer {
    2 private:
    3    static const int NumTurns = 5;
    4    int scores[NumTurns];
    5    ...   
    6 };

    另外一种方式

    1 class GamePlayer {
    2 private:
    3 enum { NumTurns = 5 };
    4 
    5 int scores[NumTurns];
    6 
    7 ...
    8 };
    // 如果你不想让别人获得一个pointer或referenct指向你的某个整数常量,enum可以帮助你实现这个约束。

    宏函数

     1 // 以a和b的较大值调用f
     2 #define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
     3 
     4 int a = 0, b = 0;
     5 CALL_WITH_MAX(++a, b); // a被累加两次
     6 CALL_WITH_MAX(++a, b+10); // a被累加一次
     7 
     8 template<typename T>
     9 inline void CallWithMax(const T& a, const T& b)
    10 {
    11   f(a > b ? a : b)  
    12 }

    忠告:

    对于单纯常量,最好以const对象或enums替换#defines.

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

  • 相关阅读:
    448-查找数组中消失的所有数字
    977 -排序数组的正方形
    爬虫小总结
    增量式爬虫
    分布式爬虫
    CrawlSpider:类,Spider的一个子类
    中间件
    中间件
    scrapy图片数据爬取之ImagesPipeline
    scrapy五大核心组件
  • 原文地址:https://www.cnblogs.com/AiLun/p/11498091.html
Copyright © 2011-2022 走看看