What is the '& operator' and how does it work?
What is the '& operator' and how does it work?
It can mean more than thing. However, I am assuming you are talking about the address of operator. When you have a variable, placing the ampersand (&) before the variable means you want the address of the variable instead of the actual value. For example:
Code:#include <iostream.h> int main() { int number=4; cout<<number;//will display 4 cout<<&number;//will display some weird #, the address of number return 0; }
actually the ampersand is after the variable:
example:
[code]
T& operator [] ...
Yeah, in the example im working with, the ampersand is used in fron of the variable:
Code:T& operator []
It means a reference to the variable after it. Think of a reference like a pointer. However, the address it refers to cannot be reassigned. Also, there is no need to dereference it when using it. Basically, think of it as an alias. For example, a reference to William Clinton might be Bill Clinton. When refering to one, it modifies both.
Code:#include <iostream.h> int main() { int number=4; int &numreference=number; cout<<number;//outputs 4 cout<<numreference;//outputs 4 number=7; cout<<number;//outputs 7 cout<<numreference;//outputs 7 return 0; }
BTW, your example means the function returns a reference to a T type.
unary operator gives you the address as previously stated, useful for passing to functions and pointers, see examples above.
as a binary operator it provides an alternative identity for a memory address, eg
Code:int number = 4; int& sameNumber = number; //& can be beside data type or identifier cout << number << endl; //prints 4 cout << sameNumber << endl; //prints 4
to gamma:
& operator: a bit operator (for binary operations)
the binary operators:
& : AND
| : OR
^ : XOR
if you have knowledge on how the boolean concept works, this shouldn't be a problem.
when using the '&' (AND) operator, you will be working with binary data so if you are working with an int, the int will be operated though binary operations (it does this anyway since machine operations are based on 1's and 0's).
so:
1 & 1 = 1
1 & 0 = 0
0 & 0 = 0
if you are working with a group of binaries,
example: 9 + 3:
9 = 1001
3 = 0011
so...
1001
+ 0011
---------
0001
1 = 0001 in binary so 9 & 3 = 1
think only with code.
write only with source.