gpt4 book ai didi

c++ - 先切片再多态

转载 作者:太空宇宙 更新时间:2023-11-04 14:05:20 25 4
gpt4 key购买 nike

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

最佳答案

what is going to be the call sequence below...

让我们看一下:

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

obj->func();

嗯,D2Base 重载了 virtual func(),所以,它会先被调用,然后 D2 将被打印出来。

D2(new D1(...))

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

D1(new D3(...))

D3 有重载函数,所以,D3::func() 会被调用,D3 会被打印。

D3(new Base)

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

D2
B
D3
B

关于c++ - 先切片再多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17248934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com