Chr*_*ris 0 c++ virtual inheritance
我无法弄清楚如何从派生类方法调用基类方法,但同时在作为参数传递的对象上应用此方法调用.
我的意思是:
class Animal
{
virtual void eat(Animal& to_be_eaten) = 0;
};
class Carnivores: public Animal
{
virtual void eat(Animal& to_be_eaten) { /*implementation here*/}
};
class Wolf : public Carnivores
{
virtual void eat(Animal& to_be_eaten)
{ /*call eat method(of Base class) of Base to_be_eaten here*/ }
}
Run Code Online (Sandbox Code Playgroud)
我想到了这样的事情
dynamic_cast<Carnivores&>(to_be_eaten).eat(*this) //and got a segmentation fault
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
谢谢!
新编辑::更新了代码
很简单:
class Derived : public Base {
virtual void eat(Animal& to_be_eaten) {
Base::eat(to_be_eaten);
// do anything you want with to_be_eaten here.
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:这对我有用:
class Animal
{
virtual void eat(Animal& to_be_eaten) = 0;
};
class Carnivores: public Animal
{
virtual void eat(Animal& to_be_eaten) { /*implementation here*/}
};
class Wolf : public Carnivores
{
virtual void eat(Animal& to_be_eaten)
{
Carnivores *c = dynamic_cast<Carnivores*>(&to_be_eaten);
if(c)
c->Carnivores::eat(*this);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我必须Base::eat公开才能从中调用它Derived.