如果仅部分覆盖重载函数,则多态性不起作用

Posted

技术标签:

【中文标题】如果仅部分覆盖重载函数,则多态性不起作用【英文标题】:Polymorphism not working if overloaded functions are being overridden only partially 【发布时间】:2012-08-20 05:38:05 【问题描述】:

今天我觉得自己像个菜鸟:

class Base

public:
    virtual void foo(int)=0;
    virtual void foo(int, int) 
    virtual void bar() 
;

class Derived : public Base

public:
    virtual void foo(int) 
;

void main()

    Derived d;
    d.bar(); // works
    d.foo(1); // works
    d.foo(1,2); // compiler error: no matching function call

我希望 dBase 继承 foo(int, int),但事实并非如此。那么我在这里错过了什么?

【问题讨论】:

【参考方案1】:

这是因为同名的基函数被隐藏了。

您需要将using 用于您未覆盖的功能:

class Derived : public Base

public:
    using Base::foo;
    virtual void foo(int)   //this hides all base methods called foo
;

【讨论】:

【参考方案2】:

它叫做Name hiding。你通过提供Derived::foo(int)来隐藏Base::foo(int, int)

【讨论】:

以上是关于如果仅部分覆盖重载函数,则多态性不起作用的主要内容,如果未能解决你的问题,请参考以下文章