VC6新建一个单文档工程;
添加一个一般类;
生成的Shape.cpp保持不变;
#include "Shape.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//
// Construction/Destruction
//
Shape::Shape()
{
}
Shape::~Shape()
{
}
Shape.h如下;area()函数是自己添加,其他代码是生成;area()函数前面有关键字virtual,这是一个虚函数,函数体简单直接返回0;继承类可以重写area()函数;
#if !defined(AFX_SHAPE_H__1484D4F4_EA07_45FE_9094_2BAF51F73303__INCLUDED_)
#define AFX_SHAPE_H__1484D4F4_EA07_45FE_9094_2BAF51F73303__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class Shape
{
public:
Shape();
virtual ~Shape();
virtual double area() const {
return 0;
}
};
#endif // !defined(AFX_SHAPE_H__1484D4F4_EA07_45FE_9094_2BAF51F73303__INCLUDED_)
从Shape类继承一个MyRect类,公共继承;
在生成代码基础上添加一些,MyRect.h如下;
#if !defined(AFX_MYRECT_H__8805CF13_2433_46BD_9B75_54E096BAC9FE__INCLUDED_)
#define AFX_MYRECT_H__8805CF13_2433_46BD_9B75_54E096BAC9FE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Shape.h"
class MyRect : public Shape
{
private:
double width, height;
public:
MyRect(double w, double h);
virtual ~MyRect();
virtual double area() const {
return width * height;
}
};
#endif // !defined(AFX_MYRECT_H__8805CF13_2433_46BD_9B75_54E096BAC9FE__INCLUDED_)
MyRect.cpp如下;
#include "stdafx.h"
#include "vtest.h"
#include "MyRect.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//
// Construction/Destruction
//
MyRect::MyRect(double w, double h)
{
width = w;
height = h;
}
MyRect::~MyRect()
{
}
MyRect类具有成员属性width和height,在构造函数中进行初始化;重写了基类Shape类的area()函数,返回width*height;
在视类cpp文件包含 #include "MyRect.h";
在OnDraw()函数使用前面的类,输出面积;
void CVtestView::OnDraw(CDC* pDC)
{
CVtestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CString str1;
Shape * pshp = new MyRect(3, 4);
str1.Format("Area: %g", pshp->area());
pDC->TextOut(50, 50, str1);
}
你也可以从Shape继承出圆形类,重写area()计算圆的面积;这就实现了多态;