• 学习1.2


    const 符号常量;
    (1)const int *a
    (2)int const *a
    (3)int * const a
    说明上面三种描述的区别;

    测试原代码:

    #include<iostream>
    using namespace std;
    int main(int argc, char* argv[])
    {
    int b = 2;
    const int *a = &b;
    const int c = 3;
    int d = 4;
    }
    (1)针对第一种情况:

    #include<iostream>
    using namespace std;
    int main(int argc, char* argv[])
    {
    int b = 2;
    const int *a = &b;
    const int c = 3;
    int d = 4;
    *a = d;
    }
     error C3892: “a”: 不能给常量赋值

    #include<iostream>
    using namespace std;
    int main(int argc, char* argv[])
    {
    int b = 2;
    const int *a = &b;
    const int c = 3;
    int d = 4;
    a
    = &d;
    }
    运行正确:a = 4(d的值)

    因此对于这种情况来说可以改变a的地址,也就是说a是个变量;但是不能*a却是个常量,不能直接改变*a的值。

    (2)

    #include<iostream>
    using namespace std;
    int main(int argc, char* argv[])
    {
    int b = 2;
    int const *a = &b;
    const int c = 3;
    int d = 4;
    *a = d;
    cout
    << *a<< endl;
    }
    error C3892: “a”: 不能给常量赋值
    代码
    #include<iostream>
    using namespace std;
    int main()
    {
    int b = 2;
    int const *a = &b;
    cout
    << a <<endl;
    const int c = 3;
    int d = 4;
    a
    = &d;
    cout
    << a <<endl;
    int e =5;
    a
    = &e;
    cout
    << a <<endl;
    cout
    << *a<< endl;
    }
    这样都可以,说明a也是个变量,只有*a是个常量。

    (3)

    #include<iostream>
    using namespace std;
    int main()
    {
    int b = 2;
    int * const a = &b;
    cout
    << a <<endl;
    const int c = 3;
    int d = 4;
    a
    = &d;
    }
    error C3892: “a”: 不能给常量赋值

    a是个常量,不能被赋值。

    #include<iostream>
    using namespace std;
    int main()
    {
    int b = 2;
    int * const a = &b;
    cout
    << a <<endl;
    const int c = 3;
    int d = 4;
    *a = d;
    }
    ok,*a是个变量

    const int * const a对于这种写法,a和*a都是常量,都不能被改变!

  • 相关阅读:
    统计单词数 OpenJ_Bailian
    整数划分 NBUT
    高精度(x ,/, +, -, %)良心模板
    binary-tree-maximum-path-sum
    2080 特殊的质数肋骨 USACO (深度优先搜索)
    1413 权势二进制
    POJ 1258
    poj 3126
    hdu 1195
    POJ 3752
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/1914923.html
Copyright © 2020-2023  润新知