结合实例详解"pure Virtual function called"

本文通过实例详细解析C++编程中遇到的'pure virtual function called'错误,探讨了在何时何地调用了纯虚函数以及错误产生的原因。内容包括:1) 实现基类Shape的area函数;2) 将Shape定义为纯虚类;3) 分析在构造函数中调用纯虚函数导致的问题,并进行调试。通过深入理解,帮助开发者避免此类错误。
摘要由CSDN通过智能技术生成

作者:阿波

链接:http://blog.csdn.net/livelylittlefish/article/details/9750593

(4年前的一篇文章,翻出来共享一下。)

本实例即为经典的讲解C++继承、虚函数、运行时多态的实例。今天我们再用它作为讲解"pure virtual functioncalled"的实例。(在某些平台上也可能输出"pure virtual methodcalled"

1. 实现基类Shapearea函数

 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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值