C++ int const 和 const int 的区别

  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;
}

猜你喜欢

转载自www.cnblogs.com/yaos/p/12099521.html