c++中的局部变量的返回?

来源:百度知道 编辑:UC知道 时间:2024/05/22 02:50:50
#include "iostream.h"
#include <stdlib.h>

class Fraction
{
int nume;
int deno;
public:
Fraction( int n=0,int d=1)
{
if( d==0)
{
cout<<"错误,分母不能为0"<<endl;
exit(1);
}

nume = n;
deno = d;
}

void show()
{
cout<<nume<<"/"<<deno<<endl;
}

friend Fraction operator+( const Fraction& f1,const Fraction& f2);

};

Fraction operator+( const Fraction& f1,const Fraction& f2)
{
Fraction f; //局部变量?
f.nume = f1.nume * f2.deno + f1.deno * f2.nume;
f.deno = f1.deno * f2.deno;
return f; //能返回?
}

void main()
{
Fraction f(1,2), g(2,3),k;
k=f+g;
k.show();
g.show();
}

能啊,按值返回后会被复制一份,然后原来的被销毁.
你平时写的一些函数,返回的整型变量什么的也是这个原理,这里对象的返回是一样的,只要不是把局部变量的地址返回就好了.