Inheritance mucking up polymorphism in C++?

£可爱£侵袭症+ 提交于 2019-12-13 02:49:10

问题


Perhaps my knowledge of inheritance and polymorphism isn't what I thought it was. Can anyone shed some light?

Setup (trivialization of problem):

class X {
};

class Y {
};

class Base {
  public:
    void f( X* ) {}
};

class Child: public Base {
  public:
    void f( Y* ) {}
};

Question: This should work, right?

int main( void ) {
  X* x = new X();
  Y* y = new Y();
  Child* c = new Child();
  c->f( x );
  c->f( y );
  return 0;
}

I get errors (GCC 4.4) to the tune of:

`no matching function for call to 'Child::f(X*&)'`
`note: candidates are: void Child::f(Y*)`

回答1:


The virtual keyword will not help you here.

Your base class Base::f is being hidden by your derived type. You need to do the following:

class Child: public Base {
  public:
    using Base::f;
    void f( Y* ) {}
};

Parashift goes into more detail.




回答2:


Your derived class' f() hides the base class' f(). You can prevent this by explicitly bringing Base::f() into the derived class' scope:

class Child: public Base {
  public:
    using Base::f;
    void f( Y* ) {}
};



回答3:


It was already answered at:

Why does an overridden function in the derived class hide other overloads of the base class?

When you declare a method on a derived class, it hides any method with the same name from the base class.



来源:https://stackoverflow.com/questions/1889996/inheritance-mucking-up-polymorphism-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!