定义一个基类Shape,在此基础上派生岀Rectangle和Circle,二者都有getArea()函 数计算对象的面积。使用Rectangle类创建一个派生类Square.

#include<iostream>
#include <iomanip>
using namespace std;
class Shape {
public:
    Shape(double r, double rl, double rw, double sl):radius(r),rlength(rl),rwidth(rw),slength(sl) {};、
    Shape();
private:
    double radius;
    double rlength;
    double rwidth;
    double slength;
};
Shape::Shape(){}
class Rectangle :public Shape {
public:
    Rectangle();
    ~Rectangle() {}
    void getArea(double a, double b) {
        cout << "The area of the Rectangle is " <<setiosflags(ios::fixed)<<setprecision(2)<<1.00*a * b << endl;
    };
};
Rectangle::Rectangle(){}
class Circle :public Shape {
public:
    Circle();
    ~Circle() {}
    void getArea(double c) {
        cout << "The area of the Circle is "<<setiosflags(ios::fixed) <<setprecision(2)<< 3.14 * c * c <<setprecision(2)<< endl;
    };
};
Circle::Circle()
{
}
class Square :public Rectangle {
public:
    Square();
    ~Square() {}
    void getArea(double d) {
        cout << "The area of the Square is "<<setiosflags(ios::fixed) <<setprecision(2)<< 1.00*d * d <<setprecision(2)<< endl;
    };
};
Square::Square(){}
int main() {
    double r, rl, rw, sl;
    Shape shape(r, rl, rw, sl);
    
    Rectangle rectangle;
    Circle circle;
    Square square;
    
    Rectangle* q;
    Circle* w;
    Square* e;
    
    q = &rectangle;
    w = &circle;
    e = &square;
    
    cout << "input the radius of circle: ";
    cin >> r;
    w->getArea(r);
    cout << endl;
    
    cout << "input the length and width of rectangle: ";
    cin >> rl >> rw;
    q->getArea(rl, rw);
    cout << endl;
    
    cout << "input the length of square: ";
    cin >> sl;
    e->getArea(sl);
    cout << endl;
    
    return 0;
}

【样例输入】

input the radius of circle: 5

input the length and width of rectangle:  4  6

input the length of square: 5

【样例输出】

The area of the Circle is 78.50

The area of the Rectangle is 24.00

The area of the Square is 25.00

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值