纯虚函数

纯虚函数说白了就是接口类,你要使用这个接口就要实现接口的方法,直接上代码。


代码:


#include <stdio.h>
#include <iostream>

/*
2015年10月25日 22:42:17
*/
/** 
  *Shape 
*/
class CShape
{   
public:
    CShape(){}
    virtual ~CShape(){}
    virtual void Draw() = 0;//纯虚函数
    //如果基类只表达一些抽象的概念,并不与具体的对象相联系,但是它又必须
    //为他的派生类提供一个公共界面,在这种情况下,可以将基类中的虚函数定
    //义成纯虚函数。纯虚函数是一种没有具体实现的特殊的函数。一个基类中有
    //一个纯虚函数时,则在他的派生类中至少有一个虚函数,否则纯虚函数是无
    //意义的。
};
/**
  *Point  
*/
class CPoint : public CShape
{   
public: 
    CPoint(){}  
    ~CPoint(){}    

    void Draw()     
    {
        printf("Hello! I am Point!\n");     
    }   
};

/**
  *Line 
*/
class CLine : public CShape
{   
public: 
    CLine(){}
    ~CLine(){}

    void Draw()     
    {   
        printf("Hello! I am Line!\n");      
    }   
};

void main()
{
    CShape* shape = new CPoint();
    //draw point
    shape->Draw();//在这里shape将会调用CPoint的Draw()函数
    delete shape;
    shape = new CLine();
    //draw Line
    shape->Draw();//而在这里shape将会调用CLIne 的Draw()函数
    delete shape;

    return ;    
}

/*
在vc++ 6.0中的输出结果为:
Hello! I am Point!
Hello! I am Line!
Press any key to continue
*/

解析


当CLine 要继承CShape的时候,就需要(必须)实现CShape中的纯虚函数。


另外一个例子


# include <iostream>
using namespace std;

/*
2015年10月26日 09:18:02
*/

class shape
{
public:
    virtual float area() = 0;
};

class triangle:public shape
{
protected:
    float h,w;
public:
    triangle(float hh,float ww)
    {
        h = hh;
        w = ww;
    }
    float area()
    {
        return h * w * 0.5;
    }
};

class rectangle:public triangle
{
public:
    rectangle (float h,float w):triangle(h,w)
    {   }
    float area()
    {
        return h * w;
    }
};

class circle:public shape
{
private:
    float radius;
public:
    circle(float r)
    {
        radius = r;
    }
    float area()
    {
        return radius * radius * 3.14; 
    }
};

float total(shape * s[],int n)
{
    float sum = 0;
    for (int i = 0; i < n; i++)
        sum += s[i]->area();
    return sum;
}

void main()
{
    shape * s[4];//指针数组
    s[0] = new triangle(3,4);
    s[1] = new rectangle(2,4);
    s[2] = new circle(5);
    s[3] = new circle(8);
    float sum = total(s,4);
    cout<<"总面积为"<<sum<<endl;
}

/*
在vc++ 6.0中的输出结果为:
总面积为293.46
Press any key to continue
*/
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值