gpt4 book ai didi

c++ - C++-派生类构造函数的行为

转载 作者:行者123 更新时间:2023-12-01 14:52:34 25 4
gpt4 key购买 nike

我正在准备考试。下面是一个示例问题的输出,方框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/

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