對於預先處理的單純常量, 可以使用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 //長寬比 /*更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/*/#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 inline a = 5, b = 0; callWithMax(++a, b); std::cout << " ; a = " << a <<std::endl; return 0; }
輸出:
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
作者:csdn部落格 Spike_King