C++虚函数

来源:互联网 发布:java后端需要学什么 编辑:程序博客网 时间:2024/04/28 08:40

参考

1. 如果不将某个函数定义为虚函数,在使用调用的是基类中的该方法

#include<iostream>using namespace std;class Shape{public:    void draw(){        cout << "画图形"<<endl;    }};class Rectangle :public Shape{public:    void draw(){        cout << "画矩形"<<endl;    }};class Round :public Shape{public:    void draw(){        cout << "画圆形"<<endl;    }};int main(){    Shape *shape;    shape = new Rectangle();    shape->draw(); //画图形    (new Rectangle())->draw();//画矩形    system("pause");    return 0;}

2. 将draw方法定义为虚函数

class shape{public:    shape(){        cout << "shape的构造函数" << endl;    }    virtual void draw(){        cout << "画图形" << endl;    }    ~shape(){        cout << "shape的析构函数" << endl;    }};class rectangle :public shape{public:    rectangle(){        cout << "rectangle的构造函数" << endl;    }    void draw(){        cout << "画矩形" << endl;    }    ~rectangle(){        cout << "shape的析构函数" << endl;    }};class round :public shape{public:    void draw(){        cout << "画圆形" << endl;    }};int main(){    shape *shape;    shape = new rectangle();    shape->draw(); //画矩形    (new rectangle())->draw();//画矩形    //system("pause");    return 0;}

3、在多态当中,一定要将基类的析构函数设置为虚函数,并将其实现。只有这样,才能够达到按对象构造的逆序来析构对象;否则析构的时候,只会析构基类的那一部分,派生类的那一部分无法析构

析构函数调用:先调用子类的析构函数,再调用父类的析构函数

构造函数调用:先调用父类的构造函数,再调用子类的构造函数

class Shape{public:    Shape(){        cout << "shape construction" << endl;    };    virtual void draw() = 0;//纯虚函数    virtual ~Shape(){ cout << "shape destruction" << endl; }};class Rectangle : public Shape{public:    Rectangle(){        cout << "rectangle construction" << endl;    };    void draw(){        cout << "rectangle draw" << endl;    }    ~Rectangle(){ cout << "rectangle destruction" << endl; }};class Round : public Shape{public:    Round(){        cout << "round construction" << endl;    };    void draw(){        cout << "round draw" << endl;    }    ~Round(){ cout << "round destruction" << endl; }};int main(){    Shape * s;    s = new Rectangle();    s->draw();    delete s;    s = new Round();    s->draw();    delete s;    return 0;}

运行结果:

这里写图片描述

0 0