设为首页 加入收藏

TOP

VS之多态虚函数的实现
2015-01-25 00:03:48 】 浏览:603
Tags:函数 实现

本文简单地介绍下如何使用多态和虚函数实现程序的调用。

使用工具:VS2008

使用语言:C++

开发步骤:

1.新建对话框程序

2.添加基类,写一个虚函数

Person.h

#pragma once

class CPerson
{
public:
	CPerson(void);
	~CPerson(void);
public:
	virtual void Eat();
};

Person.cpp

#include StdAfx.h
#include Person.h

CPerson::CPerson(void)
{
}

CPerson::~CPerson(void)
{
}

void CPerson::Eat()
{
	AfxMessageBox(_T(有个人吃了些水果...));
}

3.添加派生类,重写虚函数

Old.h

#pragma once
#include person.h

class COld : public CPerson
{
public:
	COld(void);
	~COld(void);
public:
	void Eat();
};

Old.cpp

#include StdAfx.h
#include Old.h

COld::COld(void)
{
}

COld::~COld(void)
{
}

void COld::Eat()
{
	AfxMessageBox(_T(年长者吃了些香蕉...));
}

Youth.h

#pragma once
#include person.h

class CYouth : public CPerson
{
public:
	CYouth(void);
	~CYouth(void);
public:
	void Eat();
};

Youth.cpp

#include StdAfx.h
#include Youth.h

CYouth::CYouth(void)
{
}

CYouth::~CYouth(void)
{
}

void CYouth::Eat()
{
	AfxMessageBox(_T(年青人吃了些苹果...));
}

Child.h

#pragma once
#include person.h

class CChild : public CPerson
{
public:
	CChild(void);
	~CChild(void);
public:
	void Eat();
};

Child.cpp

#include StdAfx.h
#include Child.h

CChild::CChild(void)
{
}

CChild::~CChild(void)
{
}

void CChild::Eat()
{
	AfxMessageBox(_T(小家伙吃了些葡萄...));
}

4.添加消息响应事件

VirtualFunctionDemoDlg.h

public:
	afx_msg void OnBnClickedBtnPerson();
	afx_msg void OnBnClickedBtnOld();
	afx_msg void OnBnClickedBtnYouth();
	afx_msg void OnBnClickedBtnChild();

VirtualFunctionDemoDlg.cpp

void CVirtualFunctionDemoDlg::OnBnClickedBtnPerson()
{
	//Person COld CYouth CChild
	CPerson* pPerson = NULL;
	pPerson  = new CPerson;
	pPerson->Eat();
}

void CVirtualFunctionDemoDlg::OnBnClickedBtnOld()
{
	CPerson* pPerson = NULL;
	pPerson  = new COld;
	pPerson->Eat();
}

void CVirtualFunctionDemoDlg::OnBnClickedBtnYouth()
{
	CPerson* pPerson = NULL;
	pPerson  = new CYouth;
	pPerson->Eat();
}

void CVirtualFunctionDemoDlg::OnBnClickedBtnChild()
{
	CPerson* pPerson = NULL;
	pPerson  = new CChild;
	pPerson->Eat();
}

5.实现效果

对话框界面 \

点击基类指针按钮效果:person \ \
点击派生类指针按钮效果:old

\ \

点击派生类指针按钮效果:youth

\ \

点击派生类指针按钮效果:child

\ \

好了,效果就演示到这儿了。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇在VC程序中获得资源文件中定义的.. 下一篇VC2005从开发MFC ActiveX ocx控件..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目