Problem Description
抽象类TDshape表示二维平面图形,三角形Triangle、长方形Rectangle是TDshape的派生类。
成员函数area()计算二维平面图形的面积,
成员函数printAll()输出二维平面图形的名字、面积和数据成员。
函数void fp(TDshape* p)和函数void fr(TDshape& r)是以TDshape为接口的函数,
输出二维平面图形的所有信息。
//你的代码将被嵌在这里
int main()
{
double down, height, lenght, width;
cin >> down >> height >> lenght >> width;
Triangle triangle(down, height);
Rectangle rectangle(lenght, width);
Triangle* pt = ▵
Rectangle& rr = rectangle;
cout << “******from obj:” << endl;
pt->printAll();
rr.printAll();
cout << “******from fp:” << endl;
fp(&triangle);
fp(&rectangle);
cout << “******from fr:” << endl;
fr(triangle);
fr(rectangle);
return 0;
}

Input Description
第1、2个数是三角形底和高
第3、4个数是长方形的长和宽
Sample Input
3 4 5 6
Sample Output
******from obj:
Triangle
底:3
高:4
面积:6
Rectangle
长:5
宽:6
面积:30
******from fp:
Triangle
底:3
高:4
面积:6
Rectangle
长:5
宽:6
面积:30
******from fr:
Triangle
底:3
高:4
面积:6
Rectangle
长:5
宽:6
面积:30

#include <iostream>
using namespace std;

class TDshape//抽象类
{
public:
    TDshape(){}
    virtual double area() = 0;
    virtual void printAll() = 0;
};

class Triangle :public TDshape
{
public:
    double a, b;
    Triangle(double x, double y)
    {
        a = x;
        b = y;
    }
    double area()
    {
        return a * b / 2;
    }
    void printAll()
    {
        cout << "Triangle" << endl;
        cout << "底:" << a << endl;
        cout << "高:" << b << endl;
        cout << "面积:" << area() << endl;
    }


};

class Rectangle :public TDshape
{
public:
    double c, d;
    Rectangle(double x, double y)
    {
        c = x;
        d = y;
    }
    double area()
    {
        return c * d;
    }
    void printAll()
    {
        cout << "Rectangle" << endl;
        cout << "长:" << c << endl;
        cout << "宽:" << d << endl;
        cout << "面积:" << area() << endl;
    }

};

void fp(TDshape* p)
{
    p->printAll();
}
void fr(TDshape& r)
{
    r.printAll();
}

int main()
{
    double down, height, lenght, width;//低,高,长,宽
    cin >> down >> height >> lenght >> width;
    Triangle triangle(down, height);
    Rectangle rectangle(lenght, width);
    Triangle* pt = &triangle;
    Rectangle& rr = rectangle;
    cout << "******from obj:" << endl;
    pt->printAll();
    rr.printAll();
    cout << "******from fp:" << endl;
    fp(&triangle);
    fp(&rectangle);
    cout << "******from fr:" << endl;
    fr(triangle);
    fr(rectangle);
    return 0;
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐