0

这是一个例子:

struct parent {
    int a;

    virtual void stuff() { a = 5; } //variant A
    void roundabout() { stuff(); }
    parent() { stuff(); }
};

struct child : parent {
    void stuff() override { a = 6; } //variant B
    child() : parent() {}
};

和使用

child c;  //calls variant A
auto p = reinterpret_cast<parent*>(&c);

c.stuff(); //calls variant B
c.roundabout(); //calls variant B
p->stuff(); //calls variant B
p->roundabout() //calls variant B

因此,在构造之后,无论我从课堂内部还是外部调用 stuff(),而无需明确说明 parent::stuff(),我都会得到 child::stuff(),正如预期的那样。

一个例外是仍然调用 parent::stuff() 的 parent 的构造函数,即使它是由子构造函数触发的。这真的很烦人,因为我必须在构造函数调用的函数中包含额外的逻辑,以使它们按应有的方式运行。为什么会这样?

4

1 回答 1

0

除非父实例已经存在,否则子实例不能存在。所以在 parent 的构造函数中,不能存在 child 的实例。child::stuff那么,如果没有孩子,你怎么能打电话呢?

于 2016-02-24T20:10:01.677 回答