1
#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;
}
4

1 回答 1

0

下面的调用顺序是什么......

让我们看一下:

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

obj->func();

好吧,来自的D2重载,所以,它会首先被调用并被打印出来。virtual func()BaseD2

D2(new D1(...))

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

D1(new D3(...))

D3具有重载函数,因此,D3::func()将被调用并被D3打印。

D3(new Base)

最后,B会打印出来。所以,完整的输出:

D2
B
D3
B
于 2013-06-22T09:22:16.293 回答