作者:阿波
链接:http://blog.csdn.net/livelylittlefish/article/details/9750593
(4年前的一篇文章,翻出来共享一下。)
本实例即为经典的讲解C++继承、虚函数、运行时多态的实例。今天我们再用它作为讲解"pure virtual functioncalled"的实例。(在某些平台上也可能输出"pure virtual methodcalled")
1. 实现基类Shape的area函数
file:testVirtualFunc.cpp
#include <stdio.h>
#include <stdlib.h>
#define PI 3.1415926
class Shape
{
private:
double ValuePerSquareUnit;
protected:
Shape(double valuePerSquareUnit):
ValuePerSquareUnit(valuePerSquareUnit)
{
}
public:
virtual double area() const = 0;
double value() const
{
return ValuePerSquareUnit * area();
}
virtual ~Shape()
{
printf("Shape::~Shape() is called");
}
double getPerSquareUnit()
{
return ValuePerSquareUnit;
}
};
class Rectangle : public Shape
{
private:
double Width;
double Height;
public:
Rectangle(double width, double height, double valuePerSquareUnit):
Shape(valuePerSquareUnit),Width(width),Height(height)
{
}
virtual ~Rectangle()
{
}
virtual double area() const
{
return Width * Height;
}
};
class Circle: public Shape
{
double Radius;
public:
Circle(double radius, double valuePerSquareUnit):
Shape(valuePerSquareUnit),Radius(radius)
{
}
virtual ~Circle()
{
}
virtual double area() const
{
return PI * Radius * Radius;
}
};
int main()
{
Rectangle* pr = new Rectangle(30, 20, 10);
Circle* pc = new Circle(15, 10);
//invoke Rectangle::area()
printf("rectangle: area = %.2f, PerSquareUnit = %.2f, value = %.2f\n",
pr->area(), pr->getPerSquareUnit(), pr->value());
//invoke Circle::area()
printf("circle : area = %.2f, PerSquareUnit = %.2f, value = %.2f\n",
pc->area(), pc->getPerSquareUnit(), pc->value());
Shape* shape;
shape = pr;
printf("rectangle: area = %.2f, PerSquareUnit = %.2f, value = %.2f\n",
shape->area(), shape->getPerSquareUnit(), shape->value());
shape = pc;
printf("circle : area = %.2f, PerSqu