Pergunta

I don't quite understand why the output on this is 10 10 if ri is a reference to i...

int i, &ri = i;
i = 5; 
ri = 10;
std::cout << i << " " << ri << std::endl;

Could someone clear this up for me?

Similarly,

int i = 0, &r1 = i;
double d = 1, &r2 = d;

r2 = r1;
std::cout << r2;  // output 0
i = r2;
std::cout << i;  // output 0
r1 = d;
std::cout << r1; // output 0

If i = r2 and r2 is a refrence to d when d = 1, why isn't the ouput 1? Also, when r1 = d, why isn't the output 1 as well?

Foi útil?

Solução

A reference is just like addressing the original item. Like *(& some_variable)

In your code therefore the line

r2 = r1;

sets the value of d to the value of i which is 0.

from then on all values are 0

if you replace the names r1 with ref_i and r2 to ref_d it will make sense.

Try it here:

http://ideone.com/SHxQLN

int i = 0, &ref_i = i;
double d = 1, &ref_d = d;

ref_d = ref_i;       // <<-------------------- Put value of i into d
std::cout << ref_d; 

i = ref_d;
std::cout << i;

ref_i = d;
std::cout << ref_i;  

Outras dicas

Think of reference as an alias (an alternative name) for an object. Whatever you do with a reference you do with the object it refers to. Here:

int i, &ri = i;

you say that ri is another name for i. Thus, here:

i = 5;

you set i = 5, and here

ri = 10;

you set i = 10.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top