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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM