纯虚函数

/*纯虚函数*/

#include "stdafx.h"
#include <iostream.h>

class IShape
{
public:
   //
表示这个虚函数是纯虚函数
    //
如果一个类中只要有一个纯虚函数,那么这个类就是抽象类
    //
抽象类不能创建实例

    virtual double Area() = 0;
    //
派生类中一定要把 抽象基类中纯虚函数覆盖
    //=0
仅仅表示是纯虚函数,

};

//=0
仅仅表示是纯虚函数,
double IShape::Area()
{
    return 0; 
}

class  Ellipse:public IShape
{
private:
    int m_nRadius;
public:
    Ellipse(int nRadius)
    {
        m_nRadius = nRadius;
    }
    double Area( )
    {
        return m_nRadius * m_nRadius * 3.14;
    }
};

class Rect:public IShape
{
private:
    int m_nWidth;
    int m_nHeight;
public:
    Rect(int nWidth, int nHeight)
    {
        m_nWidth = nWidth;
        m_nHeight = nHeight;
    }
    double Area( )
    {
        return m_nWidth * m_nHeight;
    }
};

double GetShapeArea( IShape* pShape )
{
    return pShape->Area();
}

int main(int argc, char* argv[])
{
    //
抽象类不能创建对象
    //IShape theShape;

   
    Rect theRect(10,20);
   
    Ellipse theEllipse(6);
   
    cout << "
矩形面积是"  << GetShapeArea(&theRect) << endl;
   
    cout << "
园形面积是"  << GetShapeArea(&theEllipse) << endl;
   
    return 0;
}

原文地址:https://www.cnblogs.com/w413133157/p/1660167.html