& in function declaration return type

自闭症网瘾萝莉.ら 提交于 2020-01-09 11:55:10

问题


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; }
};

This code is taken from here.


回答1:


It means return value by reference:

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

Like

int i = 10;

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

j is a reference of i, a global variable.

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

  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.

Deference in declaration

   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

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.

Pointers are like:

                      j = &i;

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

Reference are like:

                   int &j = i;

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

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. 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).

Because as you commented, you have questions about the differences between pointers and reference variables, so I highly encourage you read the related pages from the link I have given in my answer.



来源:https://stackoverflow.com/questions/15995463/in-function-declaration-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!