📄 virtshap.cpp
字号:
//这个程序在本书所带软盘中。文件名为VIRTSHAP.CPP
//这个程序利用纯虚拟成员子程序来产生多态的图形显示。
//注意,这个程序只在某些MS-DOS支持下的C++编译器环境中运行。
#include <graphics.h> //支持图形输出和输入的头文件
#include <conio.h> //支持getche()
const int W = 50; //图形的尺寸
class shape { //基类
protected:
int xCo, yCo; //中心坐标
int linecolor; //边线颜色
int fillcolor; //填充颜色
public:
shape() //构造函数
{
xCo=0;
yCo=0;
linecolor = WHITE;
fillcolor = WHITE;
}
void set(int x, int y, int lc, int fc)
{ //设置数据
xCo=x;
yCo=y;
linecolor = lc;
fillcolor = fc;
}
void colorize() //设置颜色
{
setcolor(linecolor); //线条颜色
setlinestyle(SOLID_LINE, 0, THICK_WIDTH);
// 线条宽度
setfillstyle(SOLID_FILL, fillcolor);
//设置填充颜色
}
virtual void draw() = 0; //纯虚拟成员子程序
};
class ball : public shape {
public:
ball() : shape() //构造函数
{
}
void set(int x, int y, int lc, int fc)
{ //设置数据
shape::set(x, y, lc, fc);
}
void draw()
{
shape::colorize(); //设置颜色
circle(xCo, yCo, W); //画圆
floodfill(xCo, yCo, linecolor);
//填充圆
}
};
class rect : public shape {
public:
rect() : shape() //构造函数
{
}
void set(int x, int y, int lc, int fc)
{ //设置数据
shape::set(x, y, lc, fc);
}
void draw() //画矩形
{
shape::colorize(); //设置数据
rectangle(xCo-W, yCo-W, xCo+W, yCo+W); //画矩形
floodfill(xCo, yCo, linecolor); //填充矩形
moveto(xCo-W, yCo+W); //画对角线
lineto(xCo+W, yCo-W); //线条
}
};
class tria : public shape {
public:
tria() : shape() //构造函数
{
}
void set(int x, int y, int lc, int fc) //设置数据
{
shape::set(x, y, lc, fc);
}
void draw(); //画三角形
};
void tria::draw()
{
shape::colorize(); //设置颜色
int triarray[] = { xCo, yCo-W, //三角顶部
xCo+W, yCo+W, //右边
xCo-W, yCo+W }; //左边
fillpoly(3, triarray); //画三角形
}
void main()
{
int driver, mode;
driver = DETECT; //设置为最佳图形模式
initgraph(&driver, &mode, "\\bc45\\bgi");
shape* ptrarr[3]; //指针数组转向类 shape 的对象
ball b1; //定义三个对象
rect r1;
tria t1;
//设置数据
b1.set(100, 100, WHITE, BLUE);
r1.set(100, 210, WHITE, RED);
t1.set(100, 320, WHITE, GREEN);
ptrarr[0] = &b1; //指向三个对象
ptrarr[1] = &r1;
ptrarr[2] = &t1;
for(int j=0; j<3; j++) //画图形
ptrarr[j]->draw();
getche(); //等待用户按下某个键来继续运行
closegraph(); //关闭图形系统
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -