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;
}