简单的ctor困境 - 继承

时间:2016-02-05 14:17:47

标签: c++ constructor

以下代码的结果是什么,请说明原因:)

class Mother
{
  public:
    Mother ( ) {
        cout << "r" << endl;
    }
    ~Mother ( )
    {
        cout << "n" << endl;
    }
};
class Daughter: public Mother
{
  public:
    Daughter ( )
    {
        cout << "a" << endl;
    }
    ~Daughter ( )
    {
        cout << "b" << endl;
    }
};
void foo(Mother m){ cout<< "foo" <<endl;}
int main( )
{
    Daughter lea;
    Mother* Rachel;
    foo(lea);
}

我不知道为什么,但有人告诉我它将是: r,a,foo,n,b,n(从左到右)

为什么叫“女儿lea”会产生r和a?由于继承? 为什么“foo”会突然出现?不应该是最后一次吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

这是程序执行的流程

int main( )
{
    Daughter lea;   // <- invokes the ctor of Daughter, but after Mother
    Mother* Rachel; // Nothing happens --pointer
    foo(lea);       // foo->~Mother, ~Mother called upon exit
}                   // ~Daughter->~Mother

所以,首先,在创建lea时,它会调用Daughter的ctor。由于这来自MotherMother ctor首先被调用,然后是Daughter C ++中的ctor调用顺序为base->derived

第二行没有做任何事情,因为它是指针声明。

现在,这是有趣的部分,当我们使用foo()调用lea时,它会转换为Mother并传递给foo。退出foo后,由于foo中的~Mother的本地范围,系统会调用Mother

当程序退出时,它会破坏lea,类型为Daughter。破坏的顺序与施工顺序相反。即 derieved - &gt; base,因此〜女儿跟着〜母亲。

这就是你获得

的原因
r
a
foo
n
b
n

答案 1 :(得分:0)

您的预期输出是: -

r
a
foo
n
b
n

由于Daughter源自Mother,因此当您创建Daughter的对象时,首先会调用Mother的构造函数,即the base class。那么Daughterthe derived class。因此,你得到r&amp; a首先。

接下来是

foo因为你正在调用函数foo(你必须理解)。 n之后的foo归因于函数mfoo的析构函数。

最后,当lea被销毁时,首先调用Daughter的析构函数,然后调用Mother的析构函数。这是因为析构函数以与创建它们相反的方式释放资源。因此,您再次获得b然后n