引用变量和指针问题

时间:2011-08-09 03:09:16

标签: c++ variables pointers reference

我有一个指向整数变量的指针。然后我将此指针指定给引用变量。现在,当我将指针更改为指向其他整数变量时,引用变量的值不会更改。任何人都可以解释原因吗?

int rats = 101;
int * pt = &rats;
int & rodents = *pt;                                // outputs    
cout << "rats = " << rats;                          // 101
cout << ", *pt = " << *pt;                          // 101
cout << ", rodents = " << rodents << endl;          // 101
cout << "rats address = " << &rats;                 // 0027f940
cout << ", rodents address = " << &rodents << endl; // 0027f940
int bunnies = 50;
pt = &bunnies;

cout << "bunnies = " << bunnies;                    // 50
cout << ", rats = " << rats;                        // 101  
cout << ", *pt = " << *pt;                          // 50
cout << ", rodents = " << rodents << endl;          // 101
cout << "bunnies address = " << &bunnies;           // 0027f91c
cout << ", rodents address = " << &rodents << endl; // 0027f940

我们将pt分配给兔子,但是啮齿动物的价值仍然是101.请解释原因。

1 个答案:

答案 0 :(得分:2)

该行

int & rodents = *pt;

正在创建对pt指向的内容的引用(即rats)。它不是指针pt的引用。

稍后,当您指定pt指向bunnies时,您不希望rodents引用更改。

编辑:为了说明@Als点,请考虑以下代码:

int value1 = 10;
int value2 = 20;
int& reference = value1;
cout << reference << endl; // Prints 10
reference = value2; // Doesn't do what you might think
cout << reference << endl; // Prints 20
cout << value1 << endl; // Also prints 20

第二个reference作业更改引用自身。相反,它将赋值运算符(=)应用于引用的事物,即value1

reference将始终引用value1并且无法更改。

首先让你头脑发热有点棘手,所以我建议你看看Scott Meyer的优秀书籍Effective C++More Effective C++。他比我能更好地解释这一切。