码迷,mamicode.com
首页 > 编程语言 > 详细

[C++] Virtual Destructor(虚析构函数)

时间:2015-11-15 16:20:20      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

 

 Without Virtual Destructor(虚析构函数)

class A{

public:
    int a = 3;
    A()
    {
        cout <<"A()..."<< endl;
    }
     ~A()
    {
        cout << "~A()..." << endl;
    }
};
class B : public A{
public:
    int b;
    B(){
        cout << "B()..." << endl;
    }
    ~B(){
        cout << "~B()..." << endl;
    }
};
void main()
{
    A *a = new B;
    delete a;
    system("pause");
}
result:

A()...
B()...
~A()...
Press any key to continue . . .
没有~B(),内存泄漏!!

Virtual Destructor(虚析构函数)

class A{

public:
    int a = 3;
    A()
    {
        cout <<"A()..."<< endl;
    }
    virtual ~A()
    {
        cout << "~A()..." << endl;
    }
};
class B : public A{
public:
    int b;
    B(){
        cout << "B()..." << endl;
    }
    ~B(){
        cout << "~B()..." << endl;
    }
};
void main()
{
    A *a = new B;
    delete a;
    system("pause");
}

result:

 A()...
 B()...
 ~B()...
 ~A()...
 Press any key to continue . . .

防止内存泄漏!!

 

[C++] Virtual Destructor(虚析构函数)

标签:

原文地址:http://www.cnblogs.com/tianhangzhang/p/4966672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!