#include <iostream>
using namespace std;
struct Line
{
double x1, x2, y1, y2;
};
struct Rectangle
{
double left, right, top, bottom;
};
struct Circle
{
double x, y, r;
};
union Figure
{
Line line;
Rectangle rectangle;
Circle circle;
};
enum Shape { LINE, RECTANGLE, CIRCLE };
struct TaggedFigure
{
Shape shape;
Figure figure;
};
void input(TaggedFigure[], int);
void draw(TaggedFigure);
void draw_line(Line);
void draw_rectangle(Rectangle);
void draw_circle(Circle);
int main()
{
const int N = 100;
TaggedFigure figures[N];
input(figures, N);
for (int i = 0; i < N; i++)
draw(figures[i]);
return 0;
}
void input(TaggedFigure figures[], int n)
{
for (int i = 0; i < n; i++)
{
int shape;
cout << "请输入要绘制的图形(0:线段;1:矩形;2:圆形; -1:结束):";
cin >> shape;
if (shape == -1)
break;
switch (shape)
{
case 0:
figures[i].shape = LINE;
cout << "请输入线段的起点和终点坐标(x1, y1, x2, y2):" << endl;
cin >> figures[i].figure.line.x1
>> figures[i].figure.line.x2
>> figures[i].figure.line.y1
>> figures[i].figure.line.y2;
break;
case 1:
figures[i].shape = RECTANGLE;
cout << "请输入矩形的左上角和右下角的坐标(left, top, right, bottom):" << endl;
cin >> figures[i].figure.rectangle.left
>> figures[i].figure.rectangle.top
>> figures[i].figure.rectangle.right
>> figures[i].figure.rectangle.bottom;
break;
case 2:
figures[i].shape = CIRCLE;
cout << "请输入圆心坐标和半径(x, y ,r):" << endl;
cin >> figures[i].figure.circle.x
>> figures[i].figure.circle.y
>> figures[i].figure.circle.r;
break;
}
}
}
void draw(TaggedFigure figures)
{
switch (figures.shape)
{
case LINE:
draw_line(figures.figure.line);
break;
case RECTANGLE:
draw_rectangle(figures.figure.rectangle);
break;
case CIRCLE:
draw_circle(figures.figure.circle);
break;
}
}
//上述的程序中为给出draw_line、draw_rectangle以及draw_circle三个函数的实现。
参考:《程序设计教程》(陈家骏、郑滔编著)