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/