返回信息流class X
{
public:
int i;
X(int ii=0)
{
i=ii;
cout <<"constructor " <<this<<" "<<this->i <<endl;
}
X(const X &a)
{
i=a.i;
cout <<"copy " <<this<<" "<<this-> i <<endl;
}
~X()
{
cout <<"destructor " <<this<<" "<<this->i <<endl;
}
X& operator=(const X& rhs)
{
i = rhs.i;
cout << " assign " <<this<<" "<< this->i << endl;
return *this;
}
void modify()
{
i++;
}
};
X f1(const X& x)
{
cout<<"in f1() x的地址为"<<&x<<endl;
X ret = x;
cout<<"in f1() ret的地址为"<<&ret<<endl;
ret.modify();
cout << "..." << endl;
return ret;
}
int main()
{
X x1(10);
cout<<"in main x1的地址为"<<&x1<<endl;
X x2 = f1(x1);
cout<<"x2的地址为"<<&x2<<endl;
cout << "x2.i: " << x2.i << endl;
X x22;
x22=f1(x1);
cout<<"x22的地址为"<<&x22<<endl;
cout << "x22.i: " << x22.i << endl;
const X& x3 = f1(x1);
cout<<"x3的地址为"<<&x3<<endl;
cout<<"x3.i: "<<x3.i<<endl;
getchar();
return 0;
}
函数f1的返回值为ret,ret的作用域是什么?即在什么时候撤销ret??
函数f1返回时利用ret创建的临时变量的作用域是什么?还是是否创建了临时变量??
x2的地址和ret的地址是相同的??
当函数f1返回引用时即X& f1(const X& x)时又是什么情况??
这是一条镜像帖。来源:北邮人论坛 / soft-design / #29451同步于 2008/8/29
该镜像源已超过 30 天没有更新,可能在源站已被删除。
SoftDesign机器人发帖
[求助]关于函数返回值的??
littlefang
2008/8/29镜像同步4 回复
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
哪位给解释解释??
【 在 littlefang 的大作中提到: 】
: class X
: {
: public:
: ...................
【 在 littlefang 的大作中提到: 】
: class X
: {
: public:
: ...................
ret的作用域是f1函数体,当f1执行完后,ret被撤销。
每次当x2, x22, x3被赋值后,临时变量就撤销了。不过x3赋值
比较特殊。
x2的地址和ret的地址不相同。