代码改变世界

引用和取地址的区别

2017-02-11 12:34  雄风狂飙  阅读(672)  评论(0)    收藏  举报

 

1.引用在赋值=的左边,而取地址在赋值的右边,赋值的时候引用是左值,取址是右值。

int a = 10;

int &ref=a;

int *p = &a;

2.传参的时候,&定义的是引用,*定义的是地址

int func1(int &a);//引用

int func2(int *p);//地址

实参传递如下:

int actParam = 10;

int rlt = func1(actParam );//的是引传递的是引用

rlt = func2(&actParam );//传递的是地址

下面我们测试一下,以下语句是否正确,测试环境是VC6.0

func1(&actParam );

//编译报错为:error C2664: 'func1' : cannot convert parameter 1 from 'int *' to 'int &'A reference that is not to 'const' cannot be bound to a non-lvalue

func2(actParam );

//编译错误为:error C2664: 'func2' : cannot convert parameter 1 from 'int' to 'int *'Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast