我无法弄清楚如何从派生类方法调用基类方法,但同时将此方法调用应用于作为参数传递的对象。
我的意思是:
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*/ }
}
我想到了这样的事情
dynamic_cast<Carnivores&>(to_be_eaten).eat(*this) //and got a segmentation fault
有什么办法可以做到这一点吗?
谢谢!
新编辑:: 更新了代码
最佳答案
简单如:
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.
}
};
编辑:这对我有用:
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);
}
}
请注意,为了从 Derived
中调用它,我必须公开 Base::eat
。
关于c++ - 使用 C++,如何从派生类方法调用基类方法并将其应用于作为参数传递的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9828602/