虚函数实现多态的列子(动物叫。小型图形库)
所用的图形库是:EasyX。
首先是基类、纯虚函数base:
#pragma once
#include "easyx.h"
#include "mmsystem.h"
#include <Windows.h>
#pragma comment(lib,"winmm.lib")
class animal
{
public:
virtual void draw() = 0; //绘图的
virtual void shout() = 0; //叫声
virtual void move(int x, int y) = 0; //调用接口来获得坐标
protected:
int m_x; //坐标X
int m_y;//坐标Y
};
而后是子类(通过纯虚函数重载函数来实现多态)(举一个列子来说明)
动物类:羊的叫声图片(图片、音频全在项目目录下)
sheep.h
#pragma once
#include "base.h"
class sheep : public animal
{
public:
void draw();
void shout();
void move(int x, int y);
};
sheep.cpp
#include "sheep.h"
void sheep::draw()
{
IMAGE img;
loadimage(&img, L"羊.jpg", 200, 200, true);
putimage(m_x, m_y, &img);
}
void sheep::shout()
{
PlaySound(L"羊叫声.wav", NULL, SND_FILENAME | SND_ASYNC);
}
void sheep::move(int x, int y)
{
m_x = x;
m_y = y;
}
EasyX的图形库函数:
// 从图片文件获取图像(bmp/gif/jpg/png/tif/emf/wmf/ico)
void loadimage(
IMAGE* pDstImg, // 保存图像的 IMAGE 对象指针
LPCTSTR pImgFile, // 图片文件名
int nWidth = 0, // 图片的拉伸宽度
int nHeight = 0, // 图片的拉伸高度
bool bResize = false // 是否调整 IMAGE 的大小以适应图片
);
void putimage(
int dstX, // 绘制位置的 x 坐标
int dstY, // 绘制位置的 y 坐标
IMAGE *pSrcImg, // 要绘制的 IMAGE 对象指针
DWORD dwRop = SRCCOPY // 三元光栅操作码(详见备注)
);
WindowsApi函数:
BOOL PlaySound(
LPCTSTR pszSound,
HMODULE hmod,
DWORD fdwSound
);
Main函数:
#include "easyx.h"
#include "pig.h"
#include "dog.h"
#include "hen.h"
#include "cattle.h"
#include "sheep.h"
#include "house.h"
#include <conio.h>
#include "base.h"
#pragma warning(disable:4996)
int main()
{
MOUSEMSG m;
initgraph(640, 480);
animal* pls[] = { new pig(),new dog(),new hen(),new cattle(),new sheep(),new house() };
int pos[][2] = { {0,0},{200,0},{400,0},{0,200},{200,200},{400,200} };
for (int i = 0; i < 6; i++) {
pls[i]->move(pos[i][0], pos[i][1]);
pls[i]->draw();
}
while (!(GetAsyncKeyState(VK_ESCAPE) & 0x8000))
{
m = GetMouseMsg();
if (m.uMsg == WM_LBUTTONDOWN)
{
for (int i = 0; i < 6; i++) {
pls[i]->draw();
}
for (int i = 0; i < 6; i++) {
if ((pos[i][0] < m.x && m.x < pos[i][0] + 200) && (pos[i][1] < m.y && m.y < pos[i][1] + 200)) {
setlinecolor(0x800000);
rectangle(pos[i][0] + 1, pos[i][1] + 1, pos[i][0] + 198, pos[i][1] + 198);
pls[i]->shout();
break;
}
}
}
}
for (int i = 0; i < 6; i++) {
delete pls[i];
}
closegraph();
return 0;
}