继承在C ++中破坏了多态性? [英] Inheritance mucking up polymorphism in C++?
本文介绍了继承在C ++中破坏了多态性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
也许我对继承和多态性的了解不是我想的那样.谁能给我一些启示?
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;
}
我收到以下错误消息(GCC 4.4):
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*)`
推荐答案
virtual
关键字对您没有帮助.
The virtual
keyword will not help you here.
您的基类Base::f
被派生类型隐藏.您需要执行以下操作:
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* ) {}
};
这篇关于继承在C ++中破坏了多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文