summer_WXX 于 2015.06.09 15:50 提问

#include
using namespace std;
class zrf_Ratio
{
public:
zrf_Ratio(){}
zrf_Ratio(int r1,int r2):num(r1),den(r2){}
zrf_Ratio f1(zrf_Ratio& z)
{
int r,m=z.num,n=z.den;
while(r=z.num%z.den)
{
z.num=z.den;
z.den=r;
}
r=z.den;
z.num=m/r;
z.den=n/r;
return z;
}
friend ostream& operator<<(ostream& ostr, const zrf_Ratio& r)
{ return ostr << r.num << "/" << r.den;}

``````zrf_Ratio& operator=(const zrf_Ratio& z1)
{
zrf_Ratio a;
return a.f1(zrf_Ratio(num+z1.num,den+z1.den));
}

zrf_Ratio& operator*=(const zrf_Ratio& z2)
{
zrf_Ratio a;
return a.f1(zrf_Ratio(z2.num*z2.den,z2.den+z2.den));
}

zrf_Ratio& operator++()
{
num++;
den++;
return *this;
}

zrf_Ratio operator++(int)
{
zrf_Ratio a;
a=*this;
++ * this;
return a;
}
``````

private:
int num,den;
};
int main()
{
zrf_Ratio x(2,7),y(3,5),z;
z=x.operator=(y);
cout<<"x=(y)="<<z<<endl;
z=x*=(y);
cout<<"x*=(y)="<<z<<endl;
z++;
cout<<"z="<<z<<endl;
++z;
cout<<"z="<<z<<endl;
return 0;
}

6个回答

oyljerry      2015.06.09 17:02

91program      2015.06.09 16:51

++ * this; 这句不对吧，this 指针自加一后指向哪里呢？不能这样改变 this 指针的值。

Tiger_Zhao   2015.06.09 16:01
``````    zrf_Ratio(int r1,int r2):num(r1),den(r2){}
``````

Tiger_Zhao 回复summer_WXX: 只有`++`是对的，其它都不对，明天再试。你先搜一下“操作符重载 class”，找找例子。

Tiger_Zhao 回复summer_WXX: 这个没问题。以前没用过，见谅。

summer_WXX 这是一个构造函数，不对么？？

fcxxxer   2015.06.09 19:01

++ * this 有问题，不能这么写。

Tiger_Zhao   2015.06.10 09:28
``````    #include <iostream>
using namespace std;

class zrf_Ratio
{
public:
zrf_Ratio(){}
zrf_Ratio(int r1,int r2):num(r1),den(r2){}
zrf_Ratio& f1(zrf_Ratio& z)
{
cout<<"DEBUG:f1("<<z.num<<"/"<<z.den<<")"<<endl;
int r,m=z.num,n=z.den;
while(r=z.num%z.den)
{
z.num=z.den;
z.den=r;
}
r=z.den;
z.num=m/r;
z.den=n/r;
return z;
}
void print()
{
printf("%d/%d\n", num, den);
}
friend ostream& operator<<(ostream& ostr, const zrf_Ratio& r)
{ return ostr << r.num << "/" << r.den;}

/*
zrf_Ratio operator=(const zrf_Ratio& z1)
{
zrf_Ratio a;
return a.f1(zrf_Ratio(num+z1.num,den+z1.den));
}
*/
zrf_Ratio& operator*=(const zrf_Ratio& z2)
{
zrf_Ratio a;
return a.f1(zrf_Ratio(z2.num*z2.den,z2.den+z2.den));
}

zrf_Ratio& operator++()
{
++num;
++den;
return *this;
}

const zrf_Ratio operator++(int)
{
zrf_Ratio a(*this);
++ (*this);
return a;
}
private:
int num,den;
};

int main()
{
zrf_Ratio x(2,7),y(3,5),z;
/*
z=x.operator=(y);
cout<<"x=(y)="<<z<<endl;
*/
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
z=x*=(y);
cout<<"x*=(y)="<<z<<endl;

cout<<"z++="<<z++<<endl;
cout<<"z="<<z<<endl;

cout<<"++z="<<++z<<endl;
cout<<"z="<<z<<endl;
return 0;
}
``````

``````    x=2/7
y=3/5
DEBUG:f1(15/10)
x*=(y)=3/2
z++=3/2
z=4/3
++z=5/4
z=5/4
Press any key to continue
``````
beacon_2011   2015.06.10 15:41