为什么基类的函数重载不可访问

时间:2018-04-17 12:27:48

标签: c++ inheritance overloading c++17

考虑以下示例:

struct Base
{
    void foo()
    {
        cout << "Base foo\n";
    }

    void bar()
    {
        cout << "Base bar\n";
    }
};

struct Derivate : public Base
{
    void foo(int x)
    {
        cout << "Derivate foo\n";
    }
};

如果我们创建两个实例,比如

Base a;
Derivate b;

Base对象a可以像往常一样调用其成员函数(a.foo(); a.bar();)。

使用b时,通话b.bar()按预期工作,但由于我超载Base::foo(),因此无法拨打b.foo()

为什么?

1 个答案:

答案 0 :(得分:-1)

您没有超载Base::foo,而是隐藏了它。它仍然可以访问,可以像这样调用:

static_cast<Base &>(b).foo();
相关问题