地址运算符(&)与参考运算符(&) [英] Address-of operator (&) vs reference operator(&)

查看:148
本文介绍了地址运算符(&)与参考运算符(&)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此情况感到困惑:

声明指针:

int b =10;
int*a=&b;

此处&接受b的地址。

Here & takes the address of b.

考虑另一个示例:

/* Reference to the calling object can be returned */

Test& Test::func ()
{
   // Some processing
   return *this;
} 

这应该是一个指针,*这是对象的指向。
但是我们在这里要求将* this分配给& Test。

this should be a pointer, *this is the obeject pointed. But here we are asking to assign *this to &Test.

我们应该修改什么使函数返回地址。我们是否仍应使用Test& ?

What should we modify the code to let the function return the address. Should we still use Test& ?

推荐答案

在C ++中,有两种不同的语法单元:

In C++ there're two different syntax units:

&variable; // extracts address of variable

Type& ref = variable; // creates reference called ref to variable

简单用法示例:

int v = 5;

cout << v << endl; // prints 5
cout << &v << endl; // prints address of v

int* p;
p = &v; // stores address of v into p (p is a pointer to int)

int& r = v;

cout << r << endl; // prints 5

r = 6;

cout << r << endl; // prints 6
cout << v << endl; // prints 6 too because r is a reference to v

的引用至于在函数中使用引用,您应该google通过C ++引用传递,有很多关于它的教程。

As for using references in functions, you should google "passing by reference in C++", there're many tutorials about it.

这篇关于地址运算符(&amp;)与参考运算符(&amp;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆