PTA(十七)面向对象程序设计 实验三 7-2 利用继承,求三角形及矩形面积 (10 分)

7-2 利用继承,求三角形及矩形面积 (10 分)

给出下面的基类,要求: (1)建立基类Area的俩个派生类Rectangle(矩形)与Isosceles(三角形),让每一个派生类都包含一个函数getArea(),分别用来返回矩形与三角形的面积。用构造函数对height与width进行初始化。 (2)写出主程序,从键盘读入矩形的长和宽及三角形的底和高,输出矩形及三角形的面积。

class Area
{ double height;
double width;
public:
Area(double h,double w)
{
height=h;
width=w;
}
virtual double getArea()=0;
};

输入格式:

一共两行,第1行为矩形的长和宽,第2行位三角形的底边和高。
输出格式:

第1行为矩形的面积 第2行为三角形的面积
输入样例:

在这里给出一组输入。例如:

10 5
4.5 6.5

输出样例:

在这里给出相应的输出。例如:

the Area of Rectangle is 50
the Area of Isosceles is 14.625
收获
1 保护成员自己不能直接访问,但是可以通过成员函数访问,protected是相对于public说的。继承自己的可以访问。
2 私有成员自己也不能直接访问,但是可以通过成员函数访问,继承自己的也不能访问。

#include<iostream>
using namespace std;
class Area
{
    protected:
     double height;
     double width;
   public:
        Area(double h,double w)
        {
     height=h;
     width=w;
         }
        virtual double getArea()=0;
};
class Rectangle:public Area{
    public:
    Rectangle(double height,double width):Area(height,width){};
    double getArea(){
        return Area::width*Area::height;
    }
};
class Isosceles:public Area{
    public:
    Isosceles(double height,double width):Area(height,width){};
    double getArea(){
        return Area::width*Area::height/2;
    };
};
int main(){
    double rwidth,rheight;
    double iwidth,iheight;
    cin>>rwidth>>rheight>>iwidth>>iheight;
    Rectangle rectangel(rwidth,rheight);
    Isosceles isosceles(iwidth,iheight);
    cout<<"the Area of Rectangle is "<<rectangel.getArea()<<endl;
    cout<<"the Area of Isosceles is "<<isosceles.getArea()<<endl;
    // cin>>rwidth>>rheight;
    // Area area=Area(rwidth,rheight);
    // //cout<<area.height<<" "<<area.width;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值