首页 > 编程语言 > 详细

C++ int const 和 const int 的区别

时间:2019-12-26 02:37:00      阅读:93      评论:0      收藏:0      [点我收藏+]
  1. 如果对象不是针对,它们没有区别
int const x = 3;
const int x = 3;
  1. 如果对象是指针,它们有区别
    int* const p = &array: 指针p不能够指向其他地址
    const int* p = &array: 指针p只读&array,不能够对其进行修改

举例,

#include <iostream>
 
using namespace std;

int main()
{
    int arr[3]={1,2,3};
    int varr[3]={100,200,300};
    const int* p1 = arr;
    int* const p2 = arr;

    cout << *p1 << endl;
    cout << *p2 << endl;

    // *p1 = 22; // error
    *p2 = 22;
    cout << *p2 << endl;
    cout << arr[0] << endl;

    p1 = varr;
    cout << *p1 << endl;

    p2 = varr;//error
    return 0;
}

C++ int const 和 const int 的区别

原文:https://www.cnblogs.com/yaos/p/12099521.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!