引用(&)的作用: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