Welcome

首页 / 软件开发 / C++ / C++中使用编译器常量代替预处理常量详解

C++中使用编译器常量代替预处理常量详解2014-11-27对于预处理的单纯常量, 可以使用const类型进行代替;

在面向对象编程中, 类内的常量, 可以使用静态const成员代替,

注意类内(in-class), 静态const成员只允许使用整型常量进行赋值, 如果是其他类型, 是在类内声明, 类外定义的方式;

也可以使用"enum hack", 提供const的作用, 并且给内置(built-in)数组声明;

预处理的函数调用存在很多问题, 可以使用模板内联(template inline)代替, 也可以获得很高的效率;

具体参见代码, 及注释;

代码(/*eclipse cdt ; gcc 4.7.1*/):

/** effectivecpp.cpp**Created on: 2013.11.13*Author: Caroline*//*eclipse cdt ; gcc 4.7.1*/#include <iostream>#include <string>#include <array>#include <algorithm>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<int, NumTurns> scores;std::array<int, eNumTurns> escores;};const double GamePlayer::PI = 3.14;template<typename T>void f (T a) {std::cout << "f : " << a ;}template<typename T>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<int, GamePlayer::NumTurns> 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 <<std::endl;a = 5, b = 0;CALL_WITH_MAX(++a, b+10); //a, ++一次std::cout << " ; a = " <<a <<std::endl;//template inlinea = 5, b = 0;callWithMax(++a, b);std::cout << " ; a = " << a <<std::endl;return 0;}
输出:

ASPECT_RATIO = 1.653AspectRatio = 1.653authorName = CarolinesAuthorName = Carolinegp.scores : 1 2 3 4 5 GamePlayer::PI = 3.14f : 7 ; a = 7f : 10 ; a = 6f : 6 ; a = 6
作者:csdn博客 Spike_King