hw14_01.cpp

1、设计一个名为 Integer 的类,这个类包括:
 一个保护型的int数据成员:x
 一个不带形参的构造函数,设置x=0
 一个带形参的构造函数:Integer(int x)
 纯虚成员函数Display()
设计一个名为Rational的派生类,代表有理数,以公有方式继承Integer,这个类包括:
 一个私有型的int数据成员:y,代表分母,继承的x代表分子
 一个不带形参的构造函数,设置y=1
 一个带形参的构造函数:Rational(int x, int y)
 成员函数Display(),以 x/y 形式输出有理数,如 2/3
设计一个名为Complex的派生类,代表整型复数,以公有方式继承Integer ,这个类包括:
 一个私有型的int数据成员:y,代表虚部,继承的x代表实部
 一个不带形参的构造函数,设置y=0
 一个带形参的构造函数:Complex(int x, int y)
 成员函数Display(),输出复数,如 4-3i
实现上面三个类,并在主函数中测试:
创建有理数x=9/19和复数z=3-8i,并通过Integer类的指针在屏幕上输出x和z。(程序取名为hw14_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(){ this->x= 0;}
    Integer(int x){ this->x = x;}
    virtual void Display()=0;
protected:
    int x;
};
class Rational : public Integer
{
public:
    Rational(){ this->y= 1;}
    Rational(int a, int b) {
        int g = gcd(a, b);
        this->x = a / g;
        this->y = b / g;
    }
    void Display()  {
        if (x==0){cout<<0<<endl;return;}
        else if (y==1 and x==1) {
            cout<< 1<<endl;
            return;
        }
        cout << x << "/" << y << endl;
    }

private:
    int y;
};


class Complex : public Integer
{
public:
    Complex(){ this->y= 0;}
    Complex(int x,int y){this->x = x; this->y = y;}
    void Display() {
        if (y > 0)
            cout << x << '+' << y << 'i' << endl;
        else if (y < 0)
            cout << x << y << 'i' << endl;
        else
            cout << x << endl;
    }
private:
    int y;
};


int main()
{
    Rational X(9, 19);
	Complex Y(3, -8);
    Integer * p;
    p = &X;
    p->Display();
    p = &Y;
    p->Display();
	return 0;
}

发表评论

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

滚动至顶部