C++ const 与 指针

#include 
  
  
   
   

using namespace std;

int main()
{
    int a1 = 13;
    int a2 = 19;

    int const p1 = 0;
    const int p2 = 0;   // p1 和 p2 完全一样

/* error: invalid conversion from 'const int *' to 'int *'
   '&p1' is 'const int *'
   'p3' is 'int *'
   此处声明的p3是int*的const,自身不可变,而指向的数据可变,
   然而,现在指向的p1是const,不可变,所以编译器报错
*/ //  int * const p3 = &p1;

    int * const p3 = &a1; // ok
//  p3 = &a2; //p3 不可变, error: assignment of read-only variable 'p3'
    (*p3)++; // ok! equal a1++;

    int const * p4 = &p1;
    p4 = &a2; // ok!
//  (*p4)++; //p4 指向的数据不可变, error: increment of read-only location '* p4'

    const int * p5 = &p2; // p4 和 p5 完全一样
    p5 = &a2;
//  (*p5)++;

    const int * const p6 = &a1; // ok!
//  p6 = &a2; // error: assignment of read-only variable 'p6'
//  (*p6)++; // error: increment of read-only location '*(const int*)p6'

    const int * const p7 = &p1; // ok!
//  p7 = &a2; // 同p6
//  (*p7)++;  // 同p6

    cout << "p3 = " << p3 << ", *p3 = " << *p3 << endl;
    cout << "p4 = " << p4 << ", *p4 = " << *p4 << endl;
    cout << "p5 = " << p5 << ", *p5 = " << *p5 << endl;
    cout << "p6 = " << p6 << ", *p6 = " << *p6 << endl;
    cout << "p7 = " << p7 << ", *p7 = " << *p7 << endl;

    return 0;
}

  
  

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值