C++ 指针常量、常量指针和常指针常量

    int a = 2;
    int b = 3;
    int *const p1 = &a;//指针常量:被定义的指针变量就变成了一个指针类型的常变量,指针不可以变,指针指向的内容可以变,需要在定义的时候给定初值
    int const *p2 = &b;//常量指针:指向常量的指针变量,指针可以变,指针指向的内容不可以变,等价于const int *p2 = &b;
    int const *const p3 = &a;//常指针常量: 指针不能改变,指针指向的值也不能改变,等价于const int *const p3 = &a;
    
    // Error: Cannot assign to variable 'p3' with const-qualified type 'const int *const'
    // p3 = &a;
    
    // Error: Read-only variable is not assignable
    //*p3 = a;
    
    NSLog(@"%d,%d,%d,%d", a, b, *p1, *p2);
    NSLog(@"%p,%p,%p,%p", &a, &b, p1, p2);
    NSLog(@"p3: %d, %p", *p3, p3);
    
    // Error: Cannot assign to variable 'p1' with const-qualified type 'int *const'
    // p1 = &b;
    *p1 = b;
    
    // Error: Read-only variable is not assignable
    // *p2 = a;
    p2 = &a;
    
    NSLog(@"%d,%d,%d,%d", a, b, *p1, *p2);
    NSLog(@"%p,%p,%p,%p", &a, &b, p1, p2);
    NSLog(@"p3: %d, %p", *p3, p3);
    
    /*
     Log:
     2018-07-20 10:55:13.483435+0800 Test[23866:178166] 2,3,2,3
     2018-07-20 10:55:13.483684+0800 Test[23866:178166] 0x7ffeee4ada9c,0x7ffeee4ada98,0x7ffeee4ada9c,0x7ffeee4ada98
     2018-07-20 10:55:13.483834+0800 Test[23866:178166] p3: 2, 0x7ffeee4ada9c
     2018-07-20 10:55:13.484039+0800 Test[23866:178166] 3,3,3,3
     2018-07-20 10:55:13.484224+0800 Test[23866:178166] 0x7ffeee4ada9c,0x7ffeee4ada98,0x7ffeee4ada9c,0x7ffeee4ada9c
     2018-07-20 10:55:13.484377+0800 Test[23866:178166] p3: 3, 0x7ffeee4ada9c
     */

参考:
C++ 指针常量、常量指针和常指针常量

你可能感兴趣的:(C++ 指针常量、常量指针和常指针常量)