虚函数练习1

#include <iostream>
using namespace std;

class Base
{
protected:
    int int_i;
    double dbl_x;
    
public:
    Base()
    {
        int_i=1;
        dbl_x=1.5;
        
        cout << "Base() " << int_i << endl;
    }
    
    virtual ~Base()
    {
        cout << "~Base() " << int_i << endl;
    }
    
    virtual void print()
    {
        cout << "Base::int_i = " << int_i << endl;
        cout << "Base::dbl_x = " << dbl_x << endl;
    }
};

class Derived : public Base
{
protected:
    int int_i;
    
public:
    Derived()
    {
        int_i=2;
        dbl_x=2.5;
        
        cout << "Derived() " << int_i << endl;
    }
    
    ~Derived()
    {
        cout << "~Derived() " << int_i << endl;
    }
    
    virtual void print()
    {
        cout << "Base::int_i = " << Base::int_i << endl;
        cout << "Derived::int_i = " << int_i << endl;
        cout << "Base::dbl_x = " << Base::dbl_x << endl;
        cout << "Derived::dbl_x = " << dbl_x << endl;
    }
};

class Derived2: public Derived
{
protected:
    double dbl_x;
    
public:
    Derived2()
    {
        int_i=3;
        dbl_x=3.5;
        
        cout << "Derived2() " << int_i << endl;
    }
    
    
    ~Derived2()
    {
        cout << "~Derived2() " << int_i << endl;
    }
    
    virtual void print()
    {
        cout << "Base::int_i = " << Base::int_i << endl;
        cout << "Derived::int_i = " << Derived::int_i << endl;
        cout << "Derived2::int_i = " << int_i << endl;
        cout << "Base::dbl_x = " << Base::dbl_x << endl;
        cout << "Derived::dbl_x = " << Derived::dbl_x << endl;
        cout << "Derived2::dbl_x = " << dbl_x << endl;
    }
};

int main(int argc, const char* argv[])
{
    Derived2 d2;
    Derived d;
    Base b, *p;
    
    cout << "\n" << endl;
    
    p=&d2;
    p->print();
    
    cout << "\n" << endl;
    
    p=&d;
    p->print();
    
    cout << "\n" << endl;
    
    p=&b;
    p->print();
    
    cout << "\n" << endl;
    
    return 0;    
}
输出:

Base() 1
Derived() 2
Derived2() 3
Base() 1
Derived() 2
Base() 1


Base::int_i = 1
Derived::int_i = 3
Derived2::int_i = 3
Base::dbl_x = 2.5
Derived::dbl_x = 2.5
Derived2::dbl_x = 3.5


Base::int_i = 1
Derived::int_i = 2
Base::dbl_x = 2.5
Derived::dbl_x = 2.5


Base::int_i = 1
Base::dbl_x = 1.5


~Base() 1
~Derived() 2
~Base() 1
~Derived2() 3
~Derived() 3
~Base() 1

你可能感兴趣的:(虚函数练习1)