码迷,mamicode.com
首页 > 其他好文 > 详细

const限定符(1)

时间:2016-10-03 12:40:09      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

用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;
}

 

const限定符(1)

标签:

原文地址:http://www.cnblogs.com/lancoyun/p/5928901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!