切片然后多态

时间:2013-06-22 08:49:17

标签: c++ polymorphism

#include <iostream>
using namespace std;

namespace  Q20
{

//Base Class

class Base
{
    //Add some context to remove posting errors lol
public:
    Base(Base *b = NULL)
    {
        m_b = b;
    }
    Base *m_b;
    virtual void func()
    {
        cout << endl << "B";
        if(m_b)
        {
            m_b->func();
        }
        else
        {
            m_b = (Base *)1;
        }
        return;
    }
};

//Derived 1 Class

class D1 : public Base
{
    //Add some context to remove posting errors lol
public:
    D1(Base *b = NULL)
    {
        m_b = b;
    }
    void func(Base *b)
    {
        cout << endl << "D1";
        m_b->func();
    }
};

//Derived 2 Class

class D2 : public Base
{
    //Add some context to remove posting errors lol
public:
    D2(Base *b = NULL)
    {
        m_b = b;
    }
    void func()
    {
        cout << endl << "D2";
        m_b->func();
    }
};

//Derived 3 Class

class D3 : public Base
{
    //Add some context to remove posting errors lol
public:
    D3(Base *b = NULL)
    {
        m_b = b;
    }
    void func()
    {
        cout << endl << "D3";
        m_b->func();
    }
};

void Q20()
{
    Base *obj = new D2(new D1(new D3(new Base)));

    // The above is the confusing part is there any slicing occurring above and what
    // is going to be the call sequence below...

    obj->func();
    cout << endl;
    return;
}
};

//Posting question is tough
int main()
{
    Q20::Q20();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

  

下面的呼叫序列是什么......

让我们来看看:

Base *obj = new D2(...);

obj->func();

D2 virtual func()来自Base的{​​{1}},因此,首先会调用它,然后会打印D2

D2(new D1(...))

virtual func()中没有重载的D1功能,因此,Base::func()将被调用并且B将被打印。

D1(new D3(...))

D3功能已超载,因此会调用D3::func()并打印D3

D3(new Base)

最后,将打印B。所以,完整输出:

D2
B
D3
B