2013-11-04 21 views
0
class A 
{ 
    protected: 
    void func1() //DO I need to call this virtual? 
}; 

class B 
{ 
    protected: 
    void func1() //and this one as well? 
}; 

class Derived: public A, public B 
{ 
    public: 

    //here define func1 where in the code there is 
    //if(statement) {B::func1()} else {A::func1()} 
}; 

如何覆蓋func1?或者你可以定義它用於覆蓋多繼承函數的語法

class Derived: public A, public B 
{ 
    public: 

    void func1() 
}; 

沒有任何虛擬或重寫?我不明白可訪問性。謝謝。

+5

這不是幾乎相同的問題,你問幾分鐘之前的問題? http://stackoverflow.com/questions/19763903/multiple-inheritance-same-variable-name – dhein

+0

是的,但它是一個變量而不是一個函數。這個問題要求重寫該函數。 –

+2

但無論如何,我不明白你的問題?你不能在類定義中使用if語句,對嗎? – dhein

回答

4

倫納德烈,

覆蓋,你可以簡單地用相同名稱聲明的功能,實現在你需要一個變量的代碼中的註釋功能傳遞給衍生FUNC1()

對於例如:

#include <iostream> 

using namespace std; 

class A 
{ 
    protected: 
    void func1() { cout << "class A\n"; } //DO I need to call this virtual? 
}; 

class B 
{ 
    protected: 
    void func1() { cout << "class B\n"; } //and this one as well? 
}; 

class Derived: public A, public B 
{ 
    public: 

    //here define func1 where in the code there is 
    //if(statement) {B::func1()} else {A::func1()} 
    void func1(bool select = true) 
    { 
     if (select == true) 
     { 
      A::func1(); 
     } 
     else 
     { 
      B::func1(); 
     } 
    } 
}; 
int main() 
{ 
    Derived d; 
    d.func1();   //returns default value based on select being true 
    d.func1(true);  //returns value based on select being set to true 
    d.func1(false);  // returns value base on select being set to false 
    cout << "Hello World" << endl; 

    return 0; 
} 

這應該做你在找什麼,我已經使用了一個布爾值,因爲只有2個可能的版本,但是你可以使用一個enumint適合的情況下,更多的OPTIO納秒。

+1

謝謝。這回答了我的問題。 –

+0

沒問題,歡迎您:) – GMasucci