首页 > 其他 > 详细

析构函数virtual 与non-virtual

时间:2019-11-19 21:35:31      阅读:101      评论:0      收藏:0      [点我收藏+]

http://www.cppblog.com/aaxron/archive/2010/12/23/137293.html
一旦使用的继承机制, 如果基类没有设置为虚函数, 那么子类的析构函数很可能不会调用.
为什么是可能而不是一定呢?
因为是只会在指针的场景;

class Base
{
public:
    Base(){
        cout<<"Base Construcing"<<endl;
    }

    ~Base(){
        cout<<"Base Destrucing"<<endl;
    }

};

class Derived : public Base
{
public:
    Derived(){
        cout<<"Derived Constructing"<<endl;
    }

    ~Derived(){
        cout<<"Derived Destructing"<<endl;
    }
};

int main() {
    Base *base = new Derived;
    delete base;

cout<< "*************分割线*************"<<endl;
    Derived Derived;
    return 0;
}

下面是输出

Base Construcing
Derived Constructing
Base Destrucing
*************分割线*************
Base Construcing
Derived Constructing
Derived Destructing
Base Destrucing
  • 可以看出, 当使用父类指针的时候, 如果虚析构函数不具有多态性(virtual), 那么,Base*就只会调用Base类的析构函数,而不会去寻找子类的析构函数.
  • 也不能把Base* 改成Derived指针,因为Derived指针有一天也可能变成其他类型的父类

析构函数virtual 与non-virtual

原文:https://www.cnblogs.com/superzou/p/11892424.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!