题目描述
定义一个抽象类Shape,包含三个数据成员:名称、x和y坐标
包含五个虚函数分别是:名称以及x和y的get方法,求面积(返回0.0)、求体积(返回0.0)
包含一个纯虚函数shapeName,用于设置名称。
----
定义Point类继承Shape,在构造函数初始化x和y坐标,设置名称为"Point"
定义Circle类继承Point,新增数据r表示半径,设置名称为"Circle",其他函数根据需要自己编写
定义Cylinder类继承Circle,新增数据h表示高度,设置名称为"Cylinder",其他函数根据需要自己编写
要求上述派生类的设置名称不是在构造函数,是在........
----
编写一个全局函数Print,无返回值,含单个参数为Shape*类型,功能是输出图形的五个信息:名称、x和y坐标、面积、体积,要求输出必须使用抽象类的五个虚函数输出五个信息
输出格式看参考样例,面积和体积只需要输出整数部分(非四舍五入),圆周率为3.14159
要求程序中必须使用抽象类的......来创建Point、Circle、Cylinder类对象
输入
第一行输入一个点的X和Y坐标
第二行输入一个圆的X和Y坐标、半径
第三行输入一个柱体的X和Y坐标、半径、高度
输出
要求调用Print方法输出图形的信息,每个图形输出一行。
输入样例1
1.1 2.2
3.3 4.4 5.5
6.6 7.7 8.8 9.9
输出样例1
Point--(1.1,2.2)--0--0
Circle--(3.3,4.4)--95--0
Cylinder--(6.6,7.7)--1033--2408
思路分析
主要看要我们定义的全局函数Print,题目要求这个函数通过使用抽象类的五个虚函数来输出,坐标、面积、体积可以直接返回,那么我们的shapename函数可以返回一个string类字符串。
输出面积和体积需要将浮点型强制转换成整型输出,这样就只取整数部分。
然后主函数只定义一个基类的指针,通过这个抽象类指针来创建子类对象,并通过该指针作为参数调用Print函数输出。
AC代码
#include"iostream"
#include"string"
#include"iomanip"
using namespace std;
class Shape
{
protected:
string name;
float x, y;
public:
Shape(float x,float y):x(x),y(y){}
virtual float getx() { return x; }
virtual float gety() { return y; }
virtual float area() { return 0.0; }
virtual float volume() { return 0.0; }
virtual string shapename() = 0;
};
class Point :public Shape
{
public:
Point(float x, float y):Shape(x,y){}
virtual string shapename() { return name = "Point"; }
};
class Circle:public Point
{
protected:
float r;
public:
Circle(float x, float y,float r):Point(x,y),r(r){}
virtual float area() { return 3.14159*r*r; }
virtual string shapename() { return name = "Circle"; }
};
class Cylinder:public Circle
{
protected:
float h;
public:
Cylinder(float x, float y, float r,float h) :Circle(x,y,r),h(h){}
virtual float area() { return 2*3.14159*r*r+h*2*3.14159*r; }
virtual float volume() { return 3.14159*r*r*h; }
virtual string shapename() { return name = "Cylinder"; }
};
void Print(Shape* p)
{
cout << p->shapename()<<"--("<<p->getx()<<','<<p->gety()<<")--"<<(int)(p->area())<<"--"<<(int)(p->volume()) << endl;
}
int main()
{
float x, y, h, r;
Shape* p;
cin >> x >> y;
p = new Point(x, y);
Print(p);
cin >> x >> y >> r;
p = new Circle(x, y, r);
Print(p);
cin >> x >> y >> r >> h;
p = new Cylinder(x, y, r, h);
Print(p);
delete p;
}