c++ - 如果仅部分重载重载函数,多态性将不起作用

标签 c++ inheritance polymorphism overloading

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

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),但它没有。那么我在这里缺少什么?

最佳答案

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

你需要对你没有覆盖的函数使用using:

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

关于c++ - 如果仅部分重载重载函数,多态性将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113074/

相关文章:

C++ 子结构

c++ - 为 C++ 编写、读取和使用专用数据文件

模块及其类型的继承

c++ - 从派生指针调用虚函数而不支付 vtable 价格

java - 在继承类的 super 方法中返回 `this`

C++ : inheritance without virtuality

c++ - 根据大小自动按值或按引用传递类

c++ - 以下程序片段的可能输出?

java - 子类型 "inherit"通用接口(interface)是否使用该特定子类型 (Java) 进行参数化?

swift 。确保在子类方法的末尾调用父类(super class)方法