//Effective C++ Item02
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
//#define不能够用来定义class专属常量,记号名称ASPECT_RATIO从未被编译器看见
#define ASPECT_RATIO 1.653
const double AspectRatio = 1.653;
#define CALL_WITH_MAX(a,b) f((a)>(b)?(a):(b));
template<typename T>
inline void callWithMax(const T&a, const T&b){
f(a > b ? a : b);
}
void f(int val){
cout << val << endl;
}
class GamePlayer{
public:
//声明为static确保常量只有一份
//常量声明式,如果要使用的是整数类型(int,char,bool),只要不取地址,就可以声明并使用它们而无需提供定义式
static const int NumTurns=5;
//如果编译器不支持在声明式为常量赋值,可以使用enum
//enum{ NumTurns = 6 };
int scores[NumTurns];//这里需要用到NumTurns常量,需要在声明式中给常量赋值。如果在定义式中才给常量赋值会报错
};
//常量定义式,可以在常量声明式或常量定义式给常量赋值,但是不能够同时在声明式和定义式中都赋值,这样会报多次初始化的错误
const int GamePlayer::NumTurns;
int main(){
cout << GamePlayer::NumTurns << endl;
cout << &GamePlayer::NumTurns << endl;
//使用形似函数的宏,a的递增次数竟然取决于它被用来和谁比较
//应该使用template inline函数callWithMax来代替在宏中定义的CALL_WITH_MAX
int a = 5, b = 0;
CALL_WITH_MAX(++a, b);//a被累加2次
CALL_WITH_MAX(++a, b + 10);//a被累加1次
}
Effective C++ Item02 Note
最新推荐文章于 2023-04-24 00:51:28 发布