//const與基本數據類型 //const與指針類型 #includeusing namespace std; int main() { const int x = 10; //x = 20; 此處會報錯!!!const修飾其值改變不了 return 0; } int main() { //1.const int *p = NULL; 與 int const *p = NULL等價 int x = 3, y = 4; const int *p = &x; p = &y; //此處正確 //*p = 4;此處為錯誤的 //2.int *const p = NULL; int *const p = &x; //p = &y; 此處報錯 //3、const int * cont p = NULL; const int *const p = &x; //此處改變不了的 return 0; }
例子:
#includeusing namespace std; int main() { const int x = 3; x = 5; int x = 3; const int y = x; y = 5; int x = 3; const int * y = &x; *y = 5; int x = 3, z = 4; int *const y = &x; y = &z; const int x = 3; const int &y = x; y = &z; return 0; }
具體請查看錯誤信息:
代碼如下:
#includeusing namespace std; int main() { const int x = 3; x = 5; return 0; }
結果:
#includeusing namespace std; int main() { int x = 2; int y = 5; int const *p = &x; cout<<*p<
#includeusing namespace std; int main() { int x = 2; int y = 5; int const &z = x; z = 10; //會報錯 x = 11; return 0; }
//函數使用const
//函數使用const #includeusing namespace std; void fun(int &a, int &b) { a = 10; b = 22; } //函數有問題 //不能賦值 /* void fun1(const int &a, const int &b) { a = 33; b = 44; } */ int main() { int x = 2; int y = 5; fun(x, y); cout<<函數沒有const修飾的結果是: << x << , << y <
如果上例代碼的注釋去掉就會出現如下錯誤信息: