编写程序,声明一个基类Shape,再派生出Rectangle类和Circle类,二者都有GetArea()函数;计算对象的面积。使用程序Rectangle类创建一个派生类Square。
#include <iostream>
using namespace std;
class Shape//基类
{
private:
double R;
double l;
double w;
double s;//私有数据,分别为半径,长宽,面积
public:
Shape(double a,double b,double c,double d)
{
R=a;
l=b;
w=c;
s=d;
}//构造函数初始化
Shape(){
};//构造函数
};
class Rectangle:public Shape//长方形类
{
public:
Rectangle() {
};//构造函数
void getArea(double a,double b)//外部传入数据?
{
cout<<"面积"<<a*b<<endl;
}//面积计算
};
class Circle:public Shape
{
public:
Circle(){
};
void getArea(double c)
{
cout<<"面积为"<<3.14*c*c<<endl;
}
};
class Square:public Rectangle
{
public :
Square(){
};
void getArea(double d){
cout<<"square"<<d*d<<endl;
}
};
int main()
{
double q,w,e,r;
Shape shape(q,w,e,r);
Rectangle rectangle;
Circle circle;
Square square;//建立相应对象
Rectangle*p1;
Circle*p2;
Square*p3;
p1=&rectangle;
p2=&circle;
p3=□//赋值操作
cout<<"请输入圆的半径"<<endl;
cin>>q;
p2->getArea(q);
cout<<endl;
cout<<"请输入长方形的长和宽"<<endl;
cin>>w>>e;
p1->getArea(w,e);
cout<<endl;
cout<<"请输入正方形的边长"<<endl;
cin>>r;
p3->getArea(r);
cout<<endl;
return 0;
}