shaoguanfa 发表于 2015-1-21 16:24:41

C++快速入门 课件源码讨论之重载<<操作符

#include <iostream>
#include <string>
#include <stdlib.h>
class Rational
{
public:
        Rational(int num,int denom);
        Rational operator+(Rational rhs);
        Rational operator-(Rational rhs);
        Rational operator*(Rational rhs);
        Rational operator/(Rational rhs);
private:
        void normalize();
        int numerator;
        int denominator;
        friend std::ostream& operator<<(std::ostream& os, Rational f);
};

Rational::Rational(int num, int denom)
{
        numerator = num;
        denominator = denom;
        normalize();
}

void Rational::normalize()
{
        if (denominator<0)
        {
                numerator = -numerator;
                denominator = -denominator;
        }
        int a = abs(numerator);
        int b = abs(denominator);
        while (b>0)
        {
                int t = a%b;
                a = b;
                b = t;
        }
        numerator /= a;
        denominator /= a;
}
Rational Rational::operator+(Rational rhs)
{
        int a = numerator;
        int b = denominator;
        int c = rhs.numerator;
        int d = rhs.denominator;
        int e = a*b + c*d;
        int f = b*d;
        return Rational(e, f);
}
Rational Rational::operator-(Rational rhs)
{
        rhs.numerator =- rhs.numerator;
        return operator+(rhs);
}
Rational Rational::operator*(Rational rhs)
{
        int a = numerator;
        int b = denominator;
        int c = rhs.numerator;
        int d = rhs.denominator;
        int e = a*c;
        int f = b*d;
        return Rational(e, f);
}
Rational Rational::operator/(Rational rhs)
{
        int t = rhs.numerator;
        rhs.numerator = rhs.denominator;
        rhs.denominator = t;
        return operator*(rhs);
}
std::ostream& operator<<(std::ostream& os, Rational f);
int main()
{
        Rational f1(2, 16);
        Rational f2(7, 8);
        std::cout << f1 << "+"<< f2 << "=" << (f1 + f2) << "\n";
        std::cout << f1 << "-" << f2 << "=" << (f1- f2) << "\n";
        std::cout << f1 << "*" << f2 << "=" << (f1 *f2) << "\n";
        std::cout << f1 << "/" << f2 << "=" << (f1 /f2)<< "\n";
        return 0;
}
std::ostream& operator<<(std::ostream& os, Rational f)
{
        os << f.numerator << "/" << f.denominator;
        return os;
}
页: [1]
查看完整版本: C++快速入门 课件源码讨论之重载<<操作符