const与指针、引用

来源:互联网 发布:阿里旺旺for mac 10.9 编辑:程序博客网 时间:2024/05/22 03:11

一句话总结:注意const修饰指针和引用的范围,与变量类型无关。


#include <iostream>

using namespacestd;


int main(int argc,constchar * argv[]) {

    // insert code here...

    std::cout <<"Hello, World!\n";

    

    int a =5;

    int b =8;

    const int *p = &a;

    cout<<*p<<endl;

    int const *p1 = &a;

    cout<<*p1<<endl;

    //上面两者等价,注意const修饰的是*p,与int无关。

    //*p = 6; //*p是只读变量,不可赋值

    p = &b; //p可读可写,可以赋值

    cout<<*p<<endl;

    

    const int *const p3 = &a;//等价于int const * const p3 = &a;

    cout<<*p3<<endl;

    //*p3,p3均被const修饰,均是只读变量

    //*p3 = 6; //*p3是只读变量,不可赋值

    //p3 = &b; //p3是只读变量,不可赋值

    

    const int &y = a;//a的引用yconst修饰,只读不可修改

    cout<<y<<endl;

    a = 9;

    //y = 8; //只读变量,不可修改

    cout<<y<<endl;

   

   

    const int d =5;

    //int *e = &d; //错误*e可读可写,权限比变量d大,可以通过e修改只读变量d,风险太大,编译器禁止


    return0;

}