|
运行了一下,还是不行.以下是原代码.请看:
#include <iostream>
using namespace std;
class Fraction
{
private:
int numerator;
int denominator;
int greateComDiv(int n1,int n2);
public:
Fraction();
Fraction(int numer);
Fraction(int numer,int denom);
Fraction(const Fraction& copyFrom);
~Fraction() {}
void store(int numer,int denom);
inline void print() const;
const Fraction& operator++();
const Fraction& operator++(int);
Fraction& operator=(const Fraction& fr);
void operator+=(const Fraction& fr2);
operator float() const;
};
Fraction::Fraction()
{
numerator=0;
denominator=1;
}
Fraction::Fraction(int numer)
{
numerator=numer;
denominator=1;
}
Fraction::Fraction(int numer,int denom)
{
if(denom==0)
{
cout<<"Error: denominator is zero"<<endl;
exit(100);
}
if(denom<0)
{
denom=-denom;
numer=-numer;
}
int gcd=greateComDiv(abs(numer),abs(denom));
numer=numer/gcd;
denom=denom/gcd;
numerator=numer;
denominator=denom;
}
Fraction::Fraction(const Fraction& copyFrom)
{
numerator=copyFrom.numerator;
denominator=copyFrom.denominator;
}
void Fraction::store(int numer,int denom)
{
*this=Fraction(numer,denom);
return;
}
void Fraction::print() const
{
cout<<numerator<<"/"<<denominator;
return;
}
const Fraction& Fraction::operator ++()
{
numerator+=denominator;
return(*this);
}
const Fraction& Fraction::operator++ (int)
{
Fraction temp;temp=*this;
numerator+=denominator;
return temp;
}
Fraction& Fraction::operator =(const Fraction& fr)
{
numerator=fr.numerator;
denominator=fr.denominator;
return *this;
}
Fraction::operator float() const
{
return (static_cast<float>(numerator)/denominator);
}
void Fraction::operator +=(const Fraction& fr2)
{
numerator=(numerator*fr2.denominator)
+(fr2.numerator*denominator);
denominator*=fr2.denominator;
*this=Fraction(numerator,denominator);
return;
}
int Fraction::greateComDiv(int n1,int n2)
{
if(n2==0)
return n1;
else
return greateComDiv(n2,n1%n2);
}
int main()
{
Fraction fr1(1,5);
Fraction fr2;
fr2=fr1++;
cout<<"Postfix Increment:\nOriginal fr1: ";
fr1.print();
cout<<"Expression Value:";
fr2.print();
cout<<"Incremented fr1:";
fr1.print();
cout<<endl;
fr1.store(1,5);
fr2=++fr1;
cout<<"\nPrefix Increment:\nOriginal fr1:";
fr1.print();
cout<<"Expression Value:";
fr2.print();
cout<<"Incremented fr1:";
fr1.print();
cout<<endl;
Fraction fr3=fr2=fr1=1;
cout<<"\nConversion & Assignment:\nOriginal fr1:";
fr1.print();
cout<<"fr2:";
fr2.print();
cout<<"fr3:";
fr3.print();
cout<<endl;
fr3.store(5,-10);
cout<<"\nConversion to Float:\nConverted value of ";
fr3.print();
cout<<" is ";
cout<<fr3<<endl;
return 0;
} |
|