2015-05-05 48 views
2

說我有這兩個類,其他的一個兒子重寫方法:從另一個調用基方法

class Base 
{ 
public: 
    void someFunc() { cout << "Base::someFunc" << endl; } 
    void someOtherFunc() { 
     cout << "Base::someOtherFunc" << endl; 
     someFunc(); //calls Base:someFunc() 
    }; 

class Derived : public Base 
{ 
public: 
    void someFunc() { cout << "Derived::someFunc" << endl; } 
}; 

int main() 
{ 
    Base b* = new Derived(); 
    b->someOtherFunc(); // Calls Base::someOtherFunc() 
} 

我怎樣才能讓基類調用正確的someFunc()方法?

注:我無法編輯基類。

+1

你需要讓你不能做'someFunc'虛擬,你不能,如果你能做到't編輯'Base' :) – Drax

+0

還要注意,如果'Base'沒有虛擬析構函數,那麼你會很快下降到未定義的行爲。 – TartanLlama

+0

這正是我試圖避免XD,但如果這是唯一的方法,我必須重寫,甚至'''someOtherFunc''' – Luca

回答

3

你需要做someFunc虛擬其中,如果你不能編輯Base :)

0
class Base 
{ 
public: 
    virtual void someFunc() { cout << "Base::someFunc" << endl; } 
    void someOtherFunc() { 
     cout << "Base::someOtherFunc" << endl; 
     someFunc(); //calls Base:someFunc() 
    }; 
+0

我不能編輯基類 – Luca