2012-05-01 22 views
-1

可能重複:
How to force child same virtual function call its parent virtual function first運行基類函數,然後繼承類函數

EDIT人們完全缺少點什麼我得到的是,如果很多的類繼承基地,我不想每個人都打電話給Base::myFunction()


我真的不知道我怎麼詞這個問題,但希望它的代碼是明顯的(這可能並不實際編譯,我很快就寫):

class Base 
{ 
    bool flag = false; 

    void myFunction() 
    { 
     flag = true; 

     // here run the inherited class's myFunction() 
    } 
}; 

class A : public Base 
{ 
    void myFunction() 
    { 
     // do some clever stuff without having to set the flags here. 
    } 
}; 

int main() 
{ 
    A myClass; 
    myClass.myFunction(); // set the flags and then run the clever stuff 
    std::cout << myClass.flag << endl; // should print true 
    return 0; 
} 
+0

你的意思是'virtual void myFunction'? – Thomas

+0

見[C++ FAQ(http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.5)來解釋 – EdChum

回答

4

首先 - 如果您使用指針,則使用虛擬函數。 然後你只需要調用基類myFunction的在派生類中實現。 見例如:

class Base 
{ 
    bool flag = false; 

    virtual void myFunction() 
    { 
     flag = true; 
    } 
}; 

class A : public Base 
{ 
    virtual void myFunction() 
    { 
     Base::myFunction(); // call base class implementation first 
     // do some clever stuff without having to set the flags here. 
    } 
}; 

int main() 
{ 
    A myClass; 

    myClass.myFunction(); // set the flags and then run the clever stuff 

    std::cout << myClass.flag << endl; // should print true 

    return 0; 
} 

如果你不喜歡叫你的基類的功能在所有派生類。您可以爲「聰明」計算添加特殊的虛函數,並在所有派生類中分別實現它。 實施例:

class Base 
{ 
    bool flag = false; 

    virtual void cleverCalc() = 0; 
    virtual void myFunction() 
    { 
     flag = true; 
     cleverCalc(); 
    } 
}; 

class A : public Base 
{ 
    virtual void cleverCalc() 
    { 
     // do some clever stuff without having to set the flags here. 
    } 
}; 
+0

我已經知道這個方法,並希望避免它....但其最接近的答案,所以我必須接受它。 – Cheetah

3
class A : public Base 
{ 
    void myFunction() 
    { 
     Base::myFunction(); // <------------------------------- 
     // do some clever stuff without having to set the flags here. 
    } 
}; 
+0

什麼我得到的是,如果很多的類繼承的基礎,我不希望每一個都調用'Base :: myFunction()'! – Cheetah

+0

@Ben然後讓你的動作成爲構造函數的一部分。這是真正自動從基類中調用某些東西的唯一方法。 – chrisaycock

+0

@chrisaycock - 不可能做我想要的東西......謝謝。 – Cheetah

0

藉助於您的繼承結構的,在派生類myFunction的()調用排除了在基類中的版本呼叫,從而標誌被從未設置爲「真」。

2

你讓另一個函數空的實現(將在子類將覆蓋),並調用你的myFunction。這樣的事情:

class Base 
{ 
    bool flag = false; 

    void myFunction() 
    { 
     flag = true; 

     // here run the inherited class's myFunction() 
     myDerivedFunction(); 
    } 

    virtual void myDerivedFunction() 
    { 
     // this should be implemented by subclasses. 
    } 
}; 

class A : public Base 
{ 
    void myDerivedFunction() 
    { 
     // do some clever stuff without having to set the flags here. 
    } 
}; 
+0

+1強制子類實現你可以做'myDerivedFunction()'純虛。 – hmjd