&在函数声明返回类型 [英] & in function declaration return type

查看:106
本文介绍了&在函数声明返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是&在下面是什么意思?

What does the & mean in the following?

class Something
{
 public:
   int m_nValue;

   const int& GetValue() const { return m_nValue; }
   int& GetValue() { return m_nValue; }
};

此代码取自这里

推荐答案

   int& GetValue()
     ^ Means returns a reference of int

int i = 10;

int& GetValue() {
    int &j = i;
    return j;
}

注意:在C ++中有三种变量:

Note: In C++ you have three kinds of variables:


  1. 值变量例如 int i = 10

  2. 引用变量例如 int& j = i;
    引用变量创建其他变量的别名,都是同一内存位置的符号名称。

  3. 地址变量: int * ptr =& i 。称为指针。指针变量用于保存变量的地址。

  1. Value variable for example int i = 10.
  2. Reference variable for example int &j = i; reference variable creates alias of other variable, both are symbolic names of same memory location.
  3. Address variable: int* ptr = &i. called pointers. Pointer variables use for holding address of a variable.

声明中的参数

   Pointer:
           int  *ptr = &i;
                ^      ^  & is on the left side as an address operation
                |
                * For pointer variable.

   Reference:

           int &j = i;
               ^
               | & on the right side for reference

记住在C你只有两种变量值和地址)。引用变量在C ++中,引用很容易使用,如值变量和指针变量一样。

Remember in C you have only two kinds of variables value and address (pointer). Reference variables are in C++, and references are simple to use like value variables and as capable as pointer variables.

指针如下:

                      j = &i;

                      i                   j
                   +------+            +------+
                   | 10   |            | 200  |
                   +------+            +------+
                     202                 432

参考如下:

                   int &j = i;

                    i, j
                   +------+
                   | 10   |
                   +------+

没有给j分配内存。它是内存中相同位置的别名。

No memory is allocated for j. It's an alias of the same location in memory.

指针变量和引用变量之间的区别是什么? >

What are the differences between pointer variable and reference variable in C++?


  1. 指针可以重新分配任何次数,而引用初始化后无法重新分配。

  2. 指针可以指向NULL,而引用永远不能指向NULL

  3. 不能像指针一样获取引用的地址

  4. 没有引用算术(但你可以取一个引用指向的对象的地址,并在其上做指针算术,如& obj + 5)。

  1. A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
  2. A pointer can point to NULL while a reference can never point to NULL
  3. You can’t take the address of a reference like you can with pointers
  4. There’s no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).

因为你评论过,你对指针和引用变量之间的差异有疑问,所以我强烈建议你从我给出的链接中读取相关页面我的回答。

这篇关于&在函数声明返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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