c++ 中 virtual / 纯虚函数(析构函数)测试

#include <iostream>
#include <string>

using namespace std;

class Base 
{
    public:
        Base() {}
    public:
        virtual void print() 
        {
            cout << "Base::print()" << endl;
        }

        void bb() {
            cout << "Base::bb()" << endl;
        }
        virtual ~Base() = 0;
};

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

class Derived : public Base
{
    public:
        Derived() {}
    public:
        virtual void print() 
        {
            cout << "Derived::print()" << endl;
        }

        void bb() 
        {
            cout << "Derived::bb()" << endl;
        }
    public:
        ~Derived();
};

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

int main(int argc, char *argv[])
{
    
    Base *b = new Derived;
    b->print();
    b->Base::print();
    delete b;
    b = NULL;
    
    Derived dd, *pd = NULL;
    b = &dd;
    b->bb();
    
    pd = &dd;
    pd->bb(); 

    return 0;
}

编译输出:

Derived::print()
Base::print()
Derived::~Derived()
Base::~Base()
Base::bb()
Derived::bb()
Derived::~Derived()
Base::~Base()

 

赞 (0) 评论 分享 ()