Item 2: Prefer consts, enums, and inlines to #defines
This Item might better be called "prefer the compiler to the preprocessor“
#define ASPECT_RATIO 1.653
The solution is to replace the macro with a constant:
const double Aspecratio=1.653s
When replacing
#defines with constants, two special cases are worth mentioning:
1.defining constant pointers.
const char* const authorName="Scott Meyers";
2.class-specific constants.To limit the scope of a constant to a class, you must make it a member, and to ensure there's at most one copy of the constant, you must make it a static member:
class GamePlayer
{
private:
static const int NumTurns=5; // constant declaration
int scores[NumTurns]; // use of constant
....
}
Things to Remember
-
For simple constants, prefer const objects or enums to #defines.
-
For function-like macros, prefer inline functions to #defines.

本文倡导在编程实践中优先使用编译器支持的特性如常量、枚举和内联函数来替代宏定义(#define),通过具体示例展示了如何正确地进行替换,并特别提到了类特定常量的处理方式。
206

被折叠的 条评论
为什么被折叠?



