纯虚函数

来源:互联网 发布:外国网友评论中国网络 编辑:程序博客网 时间:2024/05/29 17:32

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


代码:


#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.46Press any key to continue*/
0 0