//定义一个shape抽象类,派生出rectangle类和circle类,计算各派生类对象的面积area()
#include<iostream>
using namespace std;
const double PI=3.14;
class Shape
{
public:
virtual double area()const=0;
virtual void show()=0;
};
class Rectangle:public Shape
{
private:
int x,y;
double wid,len;
public:
Rectangle(int x,int y,double wid,double len)
{
this->x=x;
this->y=y;
this->wid=wid;
this->len=len;
}
double area()const
{
return wid*len;
}
void show()
{
cout<<"长方形的长:"<<len<<" 长方形的宽:"<<wid<<endl;
}
};
class Circle:public Shape
{
private:
double radius;
int x,y;
public:
Circle(int x,int y,double radius)
{
this->x=x;
this->y=y;
this->radius=radius;
}
double area()const
{
return PI*radius*radius;
}
void show()
{
cout<<"圆的圆心为:"<<x<<","<<y<<endl;
}
};
int main()
{
Rectangle R(1,1,2.0,3.0);
Circle C(2,2,5.0);
cout<<"长方形的面积为:"<<R.area()<<endl;
R.show();
cout<<"圆的面积为:"<<C.area()<<endl;
C.show();
return 0;
}
继承和派生的应用2
最新推荐文章于 2023-12-14 12:19:56 发布