【问题标题】:reference variable and pointer problem引用变量和指针问题
【发布时间】:2011-08-09 03:09:15
【问题描述】:

我有一个指向整数变量的指针。然后我将此指针分配给一个引用变量。现在,当我将指针更改为指向其他整数变量时,引用变量的值不会改变。谁能解释一下为什么?

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。请解释原因。

【问题讨论】:

    标签: c++ variables pointers reference


    【解决方案1】:

    线

    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++。他比我解释得更好。

    【讨论】:

    • 所以你的意思是说如果将rodents 分配给一个变量,那么它就不能再次引用任何其他变量。
    • @Naphstor:是的,你是对的。引用不能被绑定到引用任何其他变量,它们始终保持对它们所绑定到的变量的引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2021-06-07
    • 2014-01-15
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    相关资源
    最近更新 更多