使用const定义常量的一些特点与注意事项,记录如下:
1.与#define相比,const定义常量编译器可以对其进行类型检查。
2.const位置不同,定义的意义不同,以指针为例:
char *p = "Hello"; // feichan // non-const data5
const char *p = "Hello"; // 非常量指针, // 指向的内容为常量
char * const p = "Hello"; // 常量指针, // 指向的内容非常量
const char * const p = "Hello"; // 常量指针, // 指向的内容为常量
3.如果限定一个常量的作用域为某个具体的类,即常量只对该类可见,使用static,例如:
class EngineeringConstants { // this goes in the class private: // header file
static const double FUDGE_FACTOR;
...
};
// this goes in the class implementation file const double EngineeringConstants::FUDGE_FACTOR = 1.35;