const用法(1) 定义常量

来源:互联网 发布:jquery load js失效 编辑:程序博客网 时间:2024/04/30 23:51

使用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 classprivate:                          // header file
        static const double FUDGE_FACTOR;
        ...
      };
      // this goes in the class implementation fileconst double EngineeringConstants::FUDGE_FACTOR = 1.35;
    而且要注意的是,在头文件中的常量只是声明,不是定义,所以在使用的源文件中必须定义。
     

 

原创粉丝点击