c++ - 为什么无法访问基类的函数重载

标签 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()

这是为什么?

最佳答案

您没有重载 Base::foo,而是隐藏了它。而且还是可以访问的,可以这样调用:

static_cast<Base &>(b).foo();

关于c++ - 为什么无法访问基类的函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49878149/

相关文章:

java - Lombok build 者的继承

.net - 如何覆盖不可继承类中的属性?

c++ - 重载运算符以处理类对象?

c++ - 是否可以在 STL set<t> 上实现 next_permutation()

c++ - 如何正确传递小数值作为参数

c++ - 写入 bool 条件 "in full"是否会影响性能?

c++ - 双继承类型推导

javascript - json和绑定(bind)方法

java - 多参数重载函数

c++ - 解决 "only static const integral data members can be initialized within a class"编译错误