c++引用、const使用

引用(&)的作用:1、取地址(在等號右邊) 2、取別名(在等號左邊)

代碼舉例

int x=3;
int *p=&x;//取地址,初始化指針
int  &y=x;//y是x的別名
int *&q=p;//爲指針取別名

const的應用

const int x=3;
x=5;//出錯,不能對常量賦值
//
const int x=3;//與#define x 3相比,需要語法檢查
//
const int x=3;int y=5;
const int *p=&x;//等價於int const *p=&x;
*p=5;//錯誤,*p是常量
p=&y;//正確
x=5;//正確
//
int x=3;
int y=3;
int *const p=&x;
int const &z=x;
&z=y;//錯誤
z=20;//錯誤
p=&y;//錯誤,指針是常量
*p=10;//正確,x值變爲10
//函數引用,使傳入函數的變量值不變
void fun(const int &a.const int &b);
int main(){
int x=3;
int y=5;
fun(x,y);//報錯
}
void fun(const int &a,const int &b){
a=10;
b=20;
}
//如果不帶const則不會報錯,x=10,y=20





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章