effect c++ 1 const and enum
来源:互联网 发布:电脑程序员工资多少 编辑:程序博客网 时间:2024/05/21 21:22
#define ASPECT_RATIO 1.653 没有被加入 symbol table(符号表)。
解决方案是用 constant(常量)来取代 macro(宏):
const double AspectRatio = 1.653; // uppercase names are usually for
// macros, hence the name change
const char *const authorName = "Scott Meyers";
更好的 authorName 的定义方式如下:
const std::string authorName("Scott Meyers");
将一个 constant(常量)的作用范围限制在一个 class(类)内,
class GamePlayer {
private:
static const int NumTurns = 5; // constant declaration NumTurns 的declaration(声明),而不是 definition(定义)。
int scores[NumTurns]; // use of constant
...
};
你可以提供如下这样一个独立的 definition(定义):const int GamePlayer::NumTurns; // definition of NumTurns; see
你应该把它放在一个 implementation file(实现文件)而非 header file(头文件)中。因为 class constants(类属常量)的 initial value(初始值)在声明时已经提供
一个 enumerated type(枚举类型)的值可以用在一个需要 ints 的地方。所以 GamePlayer 可以被如下定义:
class GamePlayer {
private:
enum { NumTurns = 5 }; // "the enum hack" - makes
// NumTurns a symbolic name for 5
int scores[NumTurns]; // fine
...
};
// call f with the maximum of a and b
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
这样的 macro(宏)有数不清的缺点,想起来就让人头疼。
无论何时,你写这样一个 macro(宏),都必须记住为 macro body(宏体)中所有的 arguments(参数)加上括号。否则,当其他人在表达式中调用了你的 macro(宏),你将陷入麻烦。但是,即使你确实做到了这一点,你还是会看到意想不到的事情发生:
int a = 5, b = 0;
CALL_WITH_MAX(++a, b); // a is incremented twice
CALL_WITH_MAX(++a, b+10); // a is incremented once
幸运的是,你并不是必须要和这样不知所云的东西打交道。你可以通过一个 inline function(内联函数)的 template(模板)来获得 macro(宏)的效率,以及完全可预测的行为和常规函数的类型安全(参见Item 30):
template<typename T> // because we don't
inline void callWithMax(const T& a, const T& b) // know what T is, we
{ // pass by reference-to-
f(a > b ? a : b); // const - seeItem 20
}
- effect c++ 1 const and enum
- 《Effect C++》学习------条款02:尽量以const,enum,inline替换#define
- effect C++ 尽量以const, enum, inline 替换 #define
- Effective C++,rule 2,Prefer const,enum and inlines to #define
- 【C++】#define vs const 、enum & inline
- c/c++ #define const enum浅析
- 《Effect C++》学习------条款03:尽可能使用const
- const and pointer in c
- const in C and C++
- [C++]尽量以const,enum,inline替换#define
- 《Effective C++》尽量以const,enum,inline,替换#define
- C语言中-const,volatile-struct,union-enum,typedef,define
- effective C++:尽量以const、enum、inline替换#define
- 【C++】尽量以const,enum,inline 替换 #define
- c语言关键字static,const,extern,struct,enum,union
- effect C++ 尽可能使用const
- 《Effect C++》学习------条款20 :宁以pass-by-reference-to-const替换pass-by-value
- [effectiv c++]条款2:尽量以const,enum,inline替换#define(static,const定义式)
- 数据结构 --静态队列 讲解
- Android本地服务编写实践
- 两种I/O模式
- Windows 8: 将英文系统转换为中文
- java.lang.ClassCastException: android.app.Application cannot be cast to *****
- effect c++ 1 const and enum
- 提示用户进行版本更新并且发布通知监控版本下载情况
- 【Oracle 基础】序列(Sequence)
- C++ 虚函数表解析
- 黑马程序员————学习日记【15】 【交通灯管理系统】
- NYOJ - 传纸条(一)(DP)
- java项目部署在tomcat 表单提交乱码问题
- 将Vim改造为强大的IDE—Vim集成Ctags/Taglist/Cscope/Winmanager/NERDTree/OmniCppComplete
- 由JTA分布式事务Timeout值引发的锁定及解决