欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++析构函数代码实例讲解

程序员文章站 2022-05-31 23:48:55
C++析构函数代码实例讲解 #include class A { public: A() { std::cout << &q...

C++析构函数代码实例讲解

#include 

class A {
public:
    A() {
        std::cout << "A created!" << std::endl;
    }
    /* 析构函数为虚函数 */
    virtual ~A() {
        std::cout << "A destroyed!" << std::endl;
    }
};

class B : public A
{
public:
    B() {
        std::cout << "B created!" << std::endl;
    }
    ~B() {
        std::cout << "B destroyed!" << std::endl;
    }
};

class M {
public:
    M() {
        std::cout << "M created!" << std::endl;
    }
    /* 析构函数不为虚函数 */
    /*virtual*/ ~M() {
        std::cout << "M destroyed!" << std::endl;
    }
};

class N : public M
{
public:
    N() {
        std::cout << "N created!" << std::endl;
    }
    ~N() {
        std::cout << "N destroyed!" << std::endl;
    }
};

int main()
{
    std::cout << "-------------------------------------------------------------------" << std::endl;
    A *p1 = new B();
    delete p1;
    std::cout << "-------------------------------------------------------------------" << std::endl;
    M *p2 = new N();
    delete p2;
    return 0;
} 

C++析构函数代码实例讲解