您的位置:首页 > 编程语言 > C语言/C++

c++基础之const

2017-04-01 22:00 155 查看
一、const与基本数据类型

   1.const int x=3;//x不可更改

      x=6;//✘

   2.int x=4;

     const int y=x;

     y=5;//✘

二、const与指针

   1.以下两种等价

    const int *p=NULL;

    int const *p=NULL;

   注:*p不可更改//例如:*p=4;✘

        p可更改//例如:p=&y;✔

   2.以下两种等价

    const int *const p=NULL;

    int const *const p=NULL;

   注:*p不可更改

        p不可更改

三、const与引用

   1.int x=3;

     int *const p=&x;

      p=&y;//✘

   2.int x=3;const int &y=x;

      x=10;//✔

      y=10;//✘

   3.const int x =3;

     const int &y=x;

     y=5;//✘

四、对比样例

  1.const int x=5;

     int *y=&x;//✘用一个可变的指针指向不可变变量是错误的。

  2.int x=5;

    const int *y=&x;//✔权限小的指向权限大的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: