类用作模板参数时丢失继承的方法

Loss of inherited method when class used as a template parameter

本文关键字:继承 方法 参数      更新时间:2023-10-16

可能重复:
为什么派生类中的重写函数隐藏基类的其他重载?

我在用作模板参数的类中使用继承方法时遇到问题。如下所示:

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)

然而,如果我删除void f(int){}方法,编译器会找到原始方法f(D&D)。看起来原始方法被新方法遮蔽了。我想知道为什么。

您可以执行此

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

基本上,用不同的签名重新声明基类方法会隐藏所有具有相同名称的基类方法。

是的,方法B.f确实隐藏了A.f。如果你想让它在B中可用,你需要一个使用指令:
class B: public A
{
public:
    using A::f;
    void f( int ) {};
};

派生类的成员将隐藏任何具有相同名称的基类成员。为了使A::fB中可用,您需要一个using声明:

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