2016-09-21 5 views
0

C++でポインタ変数と参照変数を学習していますが、私が見たサンプルコードがあります。私はなぜ* cの値が33から22に変わったのか分かりません。誤解だ新しい値を割り当てなかったときに変数の値が変更されるのはなぜですか?

int a = 22; 
int b = 33; 
int* c = &a; //c is an int pointer pointing to the address of the variable 'a' 
int& d = b; //d is a reference variable referring to the value of b, which is 33. 
c = &b; //c, which is an int pointer and stored the address of 'a' now is assigned address of 'b' 
std::cout << "*c=" << *c << ", d=" << d << std::endl; //*c= 33 d= 33 
d = a; //d is a reference variable, so it cannot be reassigned ? 
std::cout << "*c=" << *c << ", d=" << d << std::endl; //*c= 33 d= 33 

答えて

2
d = a; //d is a reference variable, so it cannot be reassigned ? 

。この文は、dが(b)への参照である変数にa(22)という値を割り当てます。 dはどのようなものに変更されますか?その行が実行された後、したがって、bの値が22

+0

ありがとうございます! – Skipher

+0

@Skipher、よろしいですか? –

2

あるのは、ステップによって、コードのステップのこの部分を実行してみましょう:

int a = 22; 
int b = 33; 

我々は、Bに値を割り当てられました。あまり言わない。

int* c = &a; 

cは、aのアドレスを保持します。 * cはaの値で、現在は22です。

int& d = b; 

dは、reference variableとbである。これ以降、dはエイリアス bと扱われます。 dの値は、bの値でもあり、33です。

c = &b; 

cは現在bのアドレスを保持しています。 * cはbの値で、現在は33です。

d = a; 

dに22(aの値)を割り当てました。 dはbの別名であるため、bは現在22です.cはbを指しているため、* cはbの値で、現在は22です。

+0

ステップバイステップのプロセスをありがとう! – Skipher

関連する問題