小言_互联网的博客

定义几何图形类Shape作为基类,并在Shape的基础上派生出圆形Circle类和矩形Rectangle类,两个派生类都有CalculateArea()函数计算几何图形面积。

450人阅读  评论(0)

定义几何图形类Shape作为基类,并在Shape的基础上派生出圆形Circle类和矩形Rectangle类,两个派生类都有CalculateArea()函数计算几何图形面积。

#include<iostream>
using namespace std;
#define PI 3.1415926535
class Shape
{
   
public:
protected:
	double mianji;
private:
};
class Circle :public Shape
{
   
public:
	Circle();
	void CalculateArea();
	void display();
protected:
	double R;
private:
};
Circle::Circle()
{
   
	cout << "请输入圆的半径:" << endl;
	cin >> R;
}
void Circle::CalculateArea()
{
   
	mianji = PI*2 * R * R;
}
void Circle::display()
{
   
	cout << "这个圆的面积为:" << endl;
	cout << mianji << endl;
}
class Rectangle :public Shape
{
   
public:
	Rectangle();
	void CalculateArea();
	void display();
protected:
	double x;
	double y;
private:
};
Rectangle::Rectangle()
{
   
	cout << "请输入矩形的长和宽:" << endl;
	cin >> x >> y;
}
void Rectangle::CalculateArea()
{
   
	mianji = x * y;
}
void Rectangle::display()
{
   
	cout << "这个矩形的面积为:" <<mianji<< endl;
}
void main()
{
   
	Circle x;
	x.CalculateArea();
	x.display();
	Rectangle y;
	y.CalculateArea();
	y.display();
}

定义一个Point作为基类,在此基础上派生出Circle类,该类含有计算面积的成员函数,并由Circle类派生出Cylinder类,该类含有计算圆柱体的表面积和体积的成员函数。

#include<iostream>
#include<math.h>
using namespace std;
#define PI 3.1415926535
class Point
{
   
public:
	Point();
protected:
	double x;
	double y;
private:
};
Point::Point()
{
   
	cout << "请输入点的坐标:" << endl;
	cin >> x >> y;
}
class Circle:public Point
{
   
public:
	Circle();
	void display();
protected:
	double mianji;
	double R;
private:
};
Circle::Circle()
{
   
	R = sqrt(x * x + y * y);
	mianji = PI * R * R;
}
void Circle::display()
{
   
	cout << "这个圆的面积为:" << mianji<<endl;
}
class Cylinder:public Circle
{
   
public:
	Cylinder();
	void Cylindermianji();
	void Cylindertiji();
	void diaplay();
protected:
	double biaomianji;
	double tiji;
	double H;
private:
};
Cylinder::Cylinder()
{
   
	cout << "请输入圆柱体的高:" << endl;
	cin >> H;
}
void Cylinder::Cylindermianji()
{
   
	double zhouchang;
	zhouchang = 2 * PI * R;
	biaomianji = zhouchang * H + 2 * mianji;
}
void Cylinder::Cylindertiji()
{
   
	tiji = H * mianji;
}
void Cylinder::diaplay()
{
   
	cout << "圆柱的表面积为:" << biaomianji << endl;
	cout << "圆柱的体积为:" << tiji << endl;
}
void main()
{
   
	Circle y;
	y.display();
	Cylinder x;
	x.Cylindermianji();
	x.Cylindertiji();
	x.diaplay();
}

如有错误请多多指教


转载:https://blog.csdn.net/weixin_51412231/article/details/110312798
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场