c++ - C++ 中的多态性为什么不起作用?

标签 c++ polymorphism

class Base {
    public:
    virtual void f();
    void f(int);
    virtual ~Base();
};

class Derived : public Base {
public:
    void f();
};

int main()
{
    Derived *ptr = new Derived;
    ptr->f(1);
    delete ptr;
    return 0;
}

ptr->f(1);显示以下错误:“函数调用中的参数过多”。

为什么这是不可能的? derived 不是继承了 base 的所有功能并且可以自由使用其中的任何功能吗? 我可以明确地调用它并且它会起作用,但为什么不允许这样做?

最佳答案

您所看到的称为隐藏

当您覆盖 Derived 类中的函数 void f() 时,您隐藏 f< 的所有其他变体 Base 类中的函数。

您可以使用 using 关键字解决此问题:

class Derived : public Base {
public:
    using Base::f;  // Pull all `f` symbols from the base class into the scope of this class

    void f() override;  // Override the non-argument version
};

关于c++ - C++ 中的多态性为什么不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41543756/

相关文章:

c++ - 使用带有 SSL (HTTPS) 的 Boost-Beast (Asio) http 客户端

c++ - 为什么 std::condition_variable 采用 unique_lock 而不是 lock_guard?

c++ - C++ 静态成员变量在单个进程中是否具有不同的实例?

c++ - 编写虚拟网络摄像头?

使用组合映射的 Haskell 多态递归会导致无限类型错误

Swift:结果的失败类型不能是协议(protocol) - "Type ' 任何 ShadowError' 无法符合错误”

c++ - 嵌套结构属性继承

c++ - 理解 C++ 中的多态性

C++:如何在此抽象类的方法中返回抽象类

c++ - 为什么在使用带有接口(interface)指针的多态行为时没有调用析构函数?