const用法


const修饰普通变量

#include

using namespace std;

/*
    const修饰常量
    ---修饰成员变量时,必须在构造函数的参数列表中初始化
    ---修饰成员函数时,加在函数后面,并且该函数无法修改成员属性
*/

int main(int argc, char const *argv[])
{
    int x = 1;

    const int a = 10;           
    int const b = 20;
    //定义两个整形常量,以上两种写法作用一致,没有区别

    const int *c = &a;           
    //const修饰指针指向的值为常整形,
    //指针的地址可以修改,但锁指向的数据不能修改

    int * const d = &x;
    //const修饰的是指针本身,为常指针
    //即指针变量(地址)不能修改,但是指针指向的数据可以修改

    const int * const e = &a;
    //const同时修饰指针和指针指向的数据,两针皆不可修改
    
    cout << "-------------------初值---------------------" << endl;
    cout << "x = " << x << "                  " << "&x = " << &x << endl;
    cout << "a = " << a << "                 " << "&a = " << &a << endl;
    cout << "b = " << b << "                 " << "&b = " << &b << endl;
    cout << "c = " << c << "     (a的地址)" << " *c = " << *c << endl;
    cout << "d = " << d << "     (x的地址)" << " *d = " << *d << endl;
    cout << "e = " << e << "     (a的地址)" << " *e = " << *e << endl;

//    a = 200;
//    b = 300;
    int m = 80; 
    c = &m;   
/*  *c = 400;    */

//    d = &m;
     *d = 500;

//    e = &m;
 /*   *e = 600;   */

    cout << "-------------------赋值---------------------" << endl;
    cout << "x = " << x << "                " << "&x = " << &x << endl;
    cout << "a = " << a << "                 " << "&a = " << &a << endl;
    cout << "b = " << b << "                 " << "&b = " << &b << endl;
    cout << "c = " << c << "     (a的地址)" << " *c = " << *c << endl;
    cout << "d = " << d << "     (x的地址)" << " *d = " << *d << endl;
    cout << "e = " << e << "     (a的地址)" << " *e = " << *e << endl;

    
    return 0;
}
C++