我正在准备考试。下面是一个示例问题的输出,方框3使我感到困惑。
--- Block 1 ---
H
SM
2 x S
DP
--- Block 2 ---
H
SM
2 x S
DP
--- Block 3 ---
H
Copy SM
1 x S
Copy DP
--- Block 4 ---
H=
--- Block 5 ---
̃H
--- Block 6 ---
̃DP
̃S
̃SM
̃H
̃DP
̃S
̃SM
̃H
我们传递了一个
Deadpool
类型的对象来构造一个新的Deadpool
对象,因此应调用copy constructor(ctor)。由于继承,Deadpool
copy ctor应该调用Spiderman
copy ctor。然后,出于相同原因,Spiderman
copy ctor调用Hero
ctor,那么为什么会有1 x S
呢?谁叫Sword
构造函数?#include <iostream>
using namespace std;
class Weapon { };
class Sword : public Weapon {
public:
Sword(int n = 1) { cout << n << " x S" << endl; }
~Sword() { cout << " ̃S" << endl; }
};
class Hero {
Weapon* w;
public:
Hero() { cout << "H" << endl; w = new Weapon; }
~Hero() { cout << " ̃H" << endl; delete w; }
virtual const Hero& operator=(const Hero& h) { cout << "H=" << endl; return *this;}
};
class SpiderMan : public Hero {
Weapon* w;
public:
SpiderMan() { cout << "SM" << endl; w = new Weapon; }
SpiderMan(const SpiderMan& s) { cout << "Copy SM" << endl; w = new Weapon; }
virtual ~SpiderMan() { cout << " ̃SM" << endl; delete w; }
const SpiderMan& operator=(const SpiderMan& s) { cout << "SM=" << endl; return *this;}
};
class DeadPool : public SpiderMan {
Sword sword;
public:
DeadPool() : sword(2) { cout << "DP" << endl; }
DeadPool(const DeadPool& d) : SpiderMan(d) { cout << "Copy DP" << endl; }
~DeadPool() { cout << " ̃DP" << endl; }
const DeadPool& operator=(const DeadPool& d) { cout << "DP=" << endl; return *this;}
};
int main() {
cout << "--- Block 1 ---" << endl;
Hero* hero = new DeadPool;
cout << "--- Block 2 ---" << endl;
SpiderMan* spiderman = new DeadPool;
cout << "--- Block 3 ---" << endl;
DeadPool deadpool(*dynamic_cast<DeadPool*>(spiderman));
cout << "--- Block 4 ---" << endl;
*hero = *spiderman;
cout << "--- Block 5 ---" << endl;
delete hero;
cout << "--- Block 6 ---" << endl;
delete spiderman;
}
最佳答案
Who called the
Sword
constructor?
DeadPool
具有类型为sword
的数据成员Sword
,在DeadPool
的副本构造函数中未提及,因此它将由其默认构造函数初始化。这就是为什么在调用基础1 x S
的构造函数和调用SpiderMan
的构造函数之间得到输出DeadPool
的原因。
关于c++ - C++-派生类构造函数的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62146104/