我正在尝试理解返回引用的函数。为此,我编写了一个简单的程序:
#include<iostream>
using namespace std;
class test
{
int i;
friend test& func();
public:
test(int j){i=j;}
void show(){cout<<i<<endl;}
};
test& func()
{
test temp(10);
return temp; //// Address of temp=0xbfcb2874
}
int main()
{
test obj1(50); // Address of obj1=0xbfcb28a0
func()=obj1; <= Problem:The address of obj1 is not changing
obj1.show(); // // Address of obj1=0xbfcb28a0
return 0;
}
我使用 gdb 运行程序并观察到 obj1
的地址仍然保持不变,但我希望它会更改为 0xbfcb2874。我不清楚这个概念。请帮忙。
最佳答案
你的代码有几个问题:
(1) 这不是您想要返回引用的方式。 temp(10)
是一个自动(即驻留在堆栈中)变量,一旦您的程序超出 test
函数的范围,它将被销毁。显示这一点的更好方法是返回对传递的变量的引用(例如,用于调用链):
Test& func(Test& some_param) {
// Do something with some_param...
// Return it as a reference.
return some_param;
}
(2) 您正在将 obj1
的值分配给 func()
,而您想要的是分配 func() 的返回值
到一个变量。试试这个:
Test obj1(50);
Test& obj2 = func(obj1); // Address of obj2 should now be the same as obj1.
(3) func()
不必是Test
的友元。事实上,它不应该。 friend
类/函数允许类/函数访问 Test
的私有(private)成员。这不是您想要经常做的事情。
关于c++ - 返回对对象的引用不会更改 C++ 中的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2862852/