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

标签 c++ inheritance constructor

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

相关文章:

python - 如何子类化 numpy .`ma.core.masked_array` ?

c# - 避免继承树中的大量强制转换

模板方法构造函数中的 C++ 奇怪行为

constructor - 为什么 Kotlin 有两种类型的构造函数?

Java初始值?

c++ - 如何检查 SWIG 接口(interface)文件中的 Lua 版本?

c++ - vtable 的编译时检测

C++:为什么要使用同一个类进行扩展和参数化?

c++ - 如何使用opencv检测图像中的文本样式?

c++ - 使用 BOOST_FOREACH 修改 std::vector 中的指针