const限定符(1)

用const给字面常量起个名字(标识符),这个标识符就称为标识符常量;因为标识符常量的声明和是哟个形象很像变量,所以也称常变量

 

定义的一般形式:

  const  数据类型(int,double,float...)  常量名=常量值;

  数据类型   const  常量名=常量值;

 

例如:

   const float PI=3.14159f;

 

注意事项:

  常变量在定义时必须初始化;

  常变量初始化后,不允许再被复制;

#include<iostream>
using namespace std;
int main()

{
    int b = 22;
//    const int a;             Error,常量必须初始化
    const int a = 100;
//    a = 11;                     Error,常量不能重新赋值


    const int *p;            //const在*左边,表示*p为常量,经由*p不能更改指针所指向的内容
    p = &b;
//    *p = 200;                 ERROR,常量不能重新赋值

//    int * const p2             Error,p2为常量,常量要初始化
    int *const p2 = &b;        //const在*右边,表示p2为常量
    int c;
//    p2 = &c;                 Error,常量不能重新被赋值
    *p2 = 200;
    cout << b << endl;
    return 0;
}

 

posted @ 2016-10-03 11:22  傲娇的猴  阅读(168)  评论(1)    收藏  举报