C++ - 使用 编译器常量 代替 预处理常量 详解

2014-11-24 02:08:02 · 作者: · 浏览: 1
对于预处理的单纯常量, 可以使用const类型进行代替;
在面向对象 编程中, 类内的常量, 可以使用静态const成员代替,
注意类内(in-class), 静态const成员只允许使用整型常量进行赋值, 如果是其他类型, 是在类内声明, 类外定义的方式;
也可以使用"enum hack", 提供const的作用, 并且给内置(built-in)数组声明;
预处理的函数调用存在很多问题, 可以使用模板内联(template inline)代替, 也可以获得很高的效率;
具体参见代码, 及注释;
代码(/*eclipse cdt ; gcc 4.7.1*/):
在CODE上查看代码片派生到我的代码片
/* 
 * effectivecpp.cpp 
 * 
 *  Created on: 2013.11.13 
 *      Author: Caroline 
 */  
  
/*eclipse cdt ; gcc 4.7.1*/  
  
#include   
#include   
#include   
  
#include   
  
using namespace std;  
  
#define ASPECT_RATIO 1.653 //长宽比  
  
#define CALL_WITH_MAX(a, b) f((a) > (b)   (a) : (b))  
  
class GamePlayer {  
public:  
    static const int NumTurns = 5;  
    static const double PI ; //不能内类初始化非整型  
    enum {eNumTurns = 5}; //枚举类型  
    std::array scores;  
    std::array escores;  
};  
const double GamePlayer::PI = 3.14;  
  
template  
void f (T a) {  
    std::cout << "f : " << a ;  
}  
  
template  
inline void callWithMax(const T& a, const T& b)  
{  
    f(a>b   a : b);  
}  
  
int main (void) {  
  
    //预处理器定义  
    std::cout << "ASPECT_RATIO = " << ASPECT_RATIO << std::endl;  
  
    //常量定义  
    const double AspectRatio = 1.653;  
    std::cout << "AspectRatio = " << AspectRatio << std::endl;  
  
    //常量指针  
    const char* const authorName = "Caroline";  
    std::cout << "authorName = " << authorName << std::endl;  
  
    //常量指针  
    const std::string sAuthorName("Caroline");  
    std::cout << "sAuthorName = " << sAuthorName << std::endl;  
  
    //class专属常量  
    GamePlayer gp;  
    std::array
scores = { {1, 2, 3, 4, 5} }; gp.scores = scores; std::cout << "gp.scores : "; for(const auto s : gp.scores) std::cout << s << " "; std::cout << std::endl; std::cout << "GamePlayer::PI = " << GamePlayer::PI << std::endl; //测试宏 int a = 5, b = 0; CALL_WITH_MAX(++a, b); //a, ++两次 std::cout << " ; a = " << a < 在CODE上查看代码片派生到我的代码片 ASPECT_RATIO = 1.653 AspectRatio = 1.653 authorName = Caroline sAuthorName = Caroline gp.scores : 1 2 3 4 5 GamePlayer::PI = 3.14 f : 7 ; a = 7 f : 10 ; a = 6 f : 6 ; a = 6