I am kind confused about this case:
Declare a pointer:
int b =10;
int*a=&b;
Here & takes the address of b.
Consider another example:
/* Reference to the calling object can be returned */
Test& Test::func ()
{
// Some processing
return *this;
}
this should be a pointer, *this is the obeject pointed. But here we are asking to assign *this to &Test.
What should we modify the code to let the function return the address. Should we still use Test& ?
The unary address-of operator ( & ) returns the address of (that is, a pointer to) its operand. The operand of the address-of operator can be a function designator or an lvalue that refers to an object that's not a bit field.
Address operator is used to storing the address of the variable in C. This is denoted by an ampersand (&). This is also used for scanning the user input.
The & (address) operator yields a pointer to its operand. The operand must be an lvalue, a function designator, or a qualified name. It cannot be a bit field.
The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. The * is a unary operator which returns the value of object pointer by a pointer variable. It is known as value of operator.
In C++ there're two different syntax units:
&variable; // extracts address of variable
and
Type& ref = variable; // creates reference called ref to variable
Easy usage example:
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
As for using references in functions, you should google "passing by reference in C++", there're many tutorials about it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With