& in function declaration return type

前端 未结 1 2026
滥情空心
滥情空心 2020-12-12 03:25

What does the & mean in the following?

class Something
{
 public:
   int m_nValue;

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


        
相关标签:
1条回答
  • 2020-12-12 04:00

    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.

    0 讨论(0)
提交回复
热议问题