2016-02-24 94 views
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 

所以施工後,其中任何一種方式我稱之爲的東西()從內部或外部類,但沒有明確說明家長::東西()正如預期的那樣,我得到了child :: stuff()。

一個例外是仍然調用parent :: stuff()的父構造函數,即使它由子構造函數觸發。這實際上很煩人,因爲我必須在構造函數調用的函數中包含額外的邏輯,以使它們像應該那樣行爲。這是爲什麼?

+0

請注意,同樣的問題也適用於析構函數。父類構造函數不能調用子類中的虛方法,因爲直到構造父類爲止,子類纔會被構造,並且父類析構函數不能調用子類中的虛方法,因爲子類已經在父類之前遭到破壞自毀。 –

回答

0

除非父實例已經存在,否則子實例不能存在。所以在父類的構造函數中,不存在任何子實例。所以如果沒有孩子,你怎麼能撥打child::stuff

相關問題