I'm way too confused of reference return/input types. I think I can best ask my question by explaining my understanding.
When a reference is input to a function as an argument as below...
void squareByReference( int & );
int main ()
{
int z = 4;
sequareByReferece( z );
return 0;
}
int squareByReference( int &numberRef )
{
numberRef *= numberRef;
}
I understand it as in the 'squareByReference,' &numberRef is received by the function as an address to an int variable, but 'somehow' can be recognized and treated just like a normal int variable. Therefore, the line 'numberRef *= numberRef; can treat numberRef as a normal int even though it's actually an address.
I'm okay with this. I get it and no problem interpreting/coding programs.
However, when it comes down to reference return, it makes me confused too much.
int g_test = 0;
int& getNumberReference()
{
return g_test;
}
int main()
{
int& n = getNumberReference();
n = 10;
std::cout << g_test << std::endl; // prints 10
std::cout << getNumberReference() + 5 << std::endl; // prints 15
return 0;
}
My confusion is this: Why is 'n' defined as a reference int variable?! Following my previous logic, the getNumberReference() returned a reference variable, and even though it is actually an address to an int, it should be 'somehow' treated as equal to normal int variable. Therefore, it should be defined in int variable not reference to int variable! This logic works perfectly fine when it comes to the line 'std::cout << getNumberReference() + 5 << std::endl;.' It is 'somehow' treated as a normal int variable and prints 15.
Could you please correct my understanding to resolve my question on int& definition???
Aucun commentaire:
Enregistrer un commentaire