建立一个形状类Shape作为基类,派生出圆类Circle和矩形类Rectangle,求出面积并获取相关信息。具体要求如下:

1.建立一个形状类Shape作为基类,派生出圆类Circle和矩形类Rectangle,求出面积并获取相关信息。具体要求如下:
(1)形状类Shape
(a)保护数据成员
double x,y:对于不同的形状,x和y表示不同的含义,如对于圆,x和y均表示圆的半径,而对于矩形,x表示矩形的长,y表示矩形的宽。访问权限定义为保护类型是为了能被继承下去,以便派生类能直接访问x和y。
(b)公有成员函数
构造函数Shape(double _x,double _y):用_x、_y分别初始化x、y。
double GetArea():求面积,在此返回0.0。
(2)圆类Circle,从Shape公有派生
(a)公有成员函数
Circle(double r):构造函数,并用r构造基类的x和y。
double GetArea():求圆的面积。
double GetRadius():获取圆的半径。

#include<iostream>
using namespace std;
#define PI 3.14
class Shape
{
	protected:
		double x,y;
	public:
		Shape(double _x,double _y);
		double GetArea();
}; 
Shape::Shape(double _x,double _y)
{
	x=_x;
	y=_y;
}
double Shape::GetArea()
{
	return 0.0;
}
class Circle:public Shape
{
	public:
		Circle(double r);
		double GetArea();
		double GetRadius();
};
Circle::Circle(double r):Shape(r,r)  //初始化参数列表 
{
//	x=r;
//	y=r;
}
double Circle::GetArea()
{
	cout<<"circle area :"<<PI*x*x<<endl;
}
double Circle::GetRadius()
{
	cout<<"radius :"<<x<<endl;
}
class Rectangle :public Shape
{
	public:
		Rectangle(double l,double w);
		double GetArea();
		double GetLength();
		double GetWidth();
};
Rectangle::Rectangle(double l,double w) :Shape(l,w)   //初始化参数列表 
{
//	x=l;
//	y=w;
}
double Rectangle::GetArea()
{
	cout<<"rectangle area :"<<y*x<<endl;
}
double Rectangle::GetLength()
{
	cout<<"length :"<<x<<endl;
}
double Rectangle::GetWidth()
{
	cout<<"width :"<<y<<endl;
}
int main()
{
	Circle c(1);
	Rectangle r(3,4);
	c.GetRadius();
	c.GetArea();
	r.GetLength();
	r.GetWidth();
	r.GetArea();
	return 0;
}




运行结果:

猜你喜欢

转载自blog.csdn.net/mmmmmmyy/article/details/81268167
今日推荐