2012-01-20 23 views
2

可能重複:
Why does an overridden function in the derived class hide other overloads of the base class?損失繼承的方法時用作模板參數類

我有在作爲一個模板參數類使用繼承的方法有問題。像下面:

class D 
{ 
}; 

class A 
{ 
public: 
     void f(D &d){}; 
}; 

class B: public A 
{ 
public: 
     void f(int) {}; 
}; 

template<typename F> 
class C 
{ 
public: 
     void doit() { D d; f->f(d); }; 
     F *f; 
}; 

int main() 
{ 
     C<B> cb; 
     cb.doit(); 
} 

這是我在嘗試編譯:

g++ testtemplate.cpp 
testtemplate.cpp: In member function ‘void C<F>::doit() [with F = B]’: 
testtemplate.cpp:28: instantiated from here 
testtemplate.cpp:21: error: no matching function for call to ‘B::f(D&)’ 
testtemplate.cpp:14: note: candidates are: void B::f(int) 

但是,如果我刪除無效F(INT){}方法,編譯器發現原來的方法F (D &d)。看起來像原來的方法是由新的陰影。我想知道爲什麼。

+1

看http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.8 –

回答

1

是的,方法B.f隱藏A.f。如果你希望它在B可用,您需要使用指令:

class B: public A 
{ 
public: 
    using A::f; 
    void f(int) {}; 
}; 
0

派生類中的成員將隱藏任何基類成員具有相同的名稱。爲了使A::f提供B,你需要一個using聲明:

class B: public A 
{ 
public: 
    using A::f;   // <--- add this 
    void f(int) {}; 
};