hw13_01.cpp

1、继承与派生
(a) 编写函数int gcd(int a, int b),利用递归方法(辗转求余法)计算最大公约数。
(b) 设计名为Integer 的类,这个类包括:
 一个保护型的int数据成员:a
 一个不带形参的构造函数,用于设置缺省值a = 0
 一个带形参的构造函数:Integer(int a)
(c) 设计名为Fraction 的派生类,代表最简分数,以公有方式继承Integer,这个类包括:
 一个保护型的int数据成员:b,代表分母,继承的a代表分子
 一个不带形参的构造函数,用于设置缺省值a = 0, b = 1
 一个带形参的构造函数:Fraction(int a, int b); (注意分子分母要通分)
 成员函数voidDisplay(),以 a/b 形式输出有理数,如 2/3,-7/5
 以非成员函数方式重载加法“+”,实现两个分数的加法(注意分子分母要通分)
Fraction operator+(const Fraction & x, const Fraction & y)
实现这两个类,并在主函数中测试:创建分数x=2/3和y=-7/5,计算z=x+y并输出。
(程序取名为hw13_01.cpp)
#include <iostream>
#include <string>

using namespace std;

int gcd(int a, int b)
{	
    if (b == 0) return a;
    return gcd(b, a % b);
}

class Integer
{
  public:
    Integer()  {a=0;}
    Integer(int a) : a(a) {}
    friend bool operator==( const Integer &, const Integer &);
  protected:
      int a;
};
bool operator==( const Integer &x, const Integer &y) {
    if (x.a == y.a) return true;
    return false;
}

class Fraction : public Integer
{
   public:
        Fraction() : Integer(), b(1) {}
        Fraction(int a, int b) {
            int g = gcd(a, b);
            this->a = a / g;
            this->b = b / g;
        }
        void Display() const {
            if (a==0){cout<<0<<endl;return;}
            else if (b==1 and a==1) {
                cout<< 1<<endl;
                return;
            }
            cout << a << "/" << b << endl;

        }
        friend Fraction operator+(const Fraction &, const Fraction &);
      protected:
        int b;
}; 
Fraction operator+(const Fraction &f, const Fraction &g){
      return Fraction(f.a * g.b + f.b * g.a, f.b * g.b);
}

int main()
{
    Fraction x(2,3), y(-7,5),j(1,3);
    Fraction z,p;

    z = x + y;
    cout << "z = "; z.Display();
	p = x + j;
    cout<< "p = "; p.Display();
	return 0;
}

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部