2012-07-14 41 views
0

可能重複:
overloaded functions are hidden in derived class無法使用基類的方法

看來我不能直接使用在派生類從基類的方法是當它們存在在兩個重載基類和C++中的派生類。以下代碼會產生錯誤no matching function for call to ‘Derived::getTwo()’

class Base { 
public: 
    int getTwo() { 
     return 2; 
    } 
    int getTwo(int, int) { 
     return 2; 
    } 
}; 

class Derived : public Base { 
public: 
    int getValue() { 
     // no matching function for call to ‘Derived::getTwo()’ 
     return getTwo(); 
    } 
    int getTwo(int) { 
     return 2; 
    } 
}; 

如果我改變return getTwo();return ((Base*) this)->getTwo(),它的工作原理,但是這看起來醜陋給我。我怎樣才能解決這個問題?

P.S.如果有問題,我使用g ++ 4.7和std = gnu ++ c11選項。

+0

這將肯定會作爲重複關閉,但同時,快速的答案是在類範圍中將'Base :: getTwo'添加到您的Derived'定義中。 – ildjarn 2012-07-14 00:26:45

回答

1

或者:

class Derived : public Base { 
public: 
    using Base::getTwo; // Add this line 
    int getValue() { 
     // no matching function for call to ‘Derived::getTwo()’ 
     return getTwo(); 
    } 
    int getTwo(int) { 
     return 2; 
    } 
} 

或者

 return Base::getTwo(); 
+0

謝謝!你能解釋一下爲什麼這個工作嗎?或者說,爲什麼它不會呢? – RPFeltz 2012-07-14 00:35:31

+0

@RPFeltz:它被稱爲*隱藏*,基本上這個過程就是查找從最接近的上下文開始(在'getValue()'method + ADL)內部開始),並且如果找不到'getTwo ,然後檢查下一個範圍,依此類推。一旦它在一個上下文中找到標識符,就停止搜索。在你的情況下,它會在你的類中找到'int getTwo(int)',所以它不會查看其他重載的基類。這兩種替代解決方案是:使用'base :: getTwo;'將基本重載帶入派生類作用域,以便它可以在類中使用... – 2012-07-14 00:56:43

+0

...然後重載解析將選擇最合適的超載。另一種解決方法是用'base :: getTwo()'限定調用,這會告訴編譯器,你想從基類上下文中獲得'getTwo()'(即避免在當前範圍內開始查找並跳轉到'getTwo ''在基地''') – 2012-07-14 00:58:54

0

這是如何在C名稱查找++工程:

namespace N1 
{ 
    int getTwo(); 
    int getTwo(int, int); 

    namespace N2 
    { 
     int getTwo(int); 

     namespace N3 
     { 
      call getTwo(something char*); 
     } 
    } 
} 

當前上下文是N3。此層上沒有getTwo。好吧,去上層。 N2包含getTwo的一個定義。編譯器會嘗試使用這個定義並且不會訪問上面的上下文。來自N2的getTwo隱藏了所有較高層上的getTwo的所有定義。有時這會導致重載方法的混淆。

如果您添加using Base::getTwo;,則實際上會爲內部上下文添加定義代理。上下文快照的定義不可見。但代理是可見的。