问题
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:
- Value variable for example
int i = 10
. - Reference variable for example
int &j = i;
reference variable creates alias of other variable, both are symbolic names of same memory location. - 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++?
- A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
- A pointer can point to NULL while a reference can never point to NULL
- You can’t take the address of a reference like you can with pointers
- 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