crazy642535606 于 2016.09.22 18:49 提问

C++ operator+重载问题

int main()
{
frac b(1,4), c;

``````c = "1/2" + "1/4";

cout << c;

return 0;
``````

}
fraction.h:

`````` __frac(int num = 0, int den = 1);//构造1
frac(char* s);//构造2
friend frac operator + (const frac &x, const frac &y);__//重载+

``````

fraction.cpp:

`````` frac operator + (const frac &x, const frac &y)
{
frac temp;
temp.num = x.num * y.den + y.num * x.den;
temp.den = x.den * y.den;
temp.standard();
return temp;
}
``````

2个回答

leewers   2016.09.22 19:48

`````` frac a(1,2), b(1,4), c;
c = a + b;
``````
YXTS122   2016.09.22 21:14

#include＜iostream＞
using namespace std;
class Frac
{
private:
int num;
int den;
public:
Frac(int n=0,int d=1)
{
num=n;
den=d;
}
friend Frac operator+(const Frac& x,const Frac& y)
{
Frac temp;
temp.num=x.num*y.den+y.num*x.den;
temp.den=x.den*y.den;
// temp.standard();
return temp;
}
friend ostream& operator＜＜(ostream& os,Frac f)
{
os＜＜f.num＜＜"/"＜＜f.den＜＜"\n";
}
};
int main()
{
Frac a(1,2),b(1,4),c;
c=a+b;
cout＜＜c;
return 0;
}