使用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;
最后
以上就是甜美春天最近收集整理的关于const用法(1) 定义常量的全部内容,更多相关const用法(1)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复