c++ - 使用 C++,如何从派生类方法调用基类方法并将其应用于作为参数传递的对象?

标签 c++ inheritance virtual

我无法弄清楚如何从派生类方法调用基类方法,但同时将此方法调用应用于作为参数传递的对象。

我的意思是:

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/

相关文章:

C++修改基类不影响继承类

c++ - 为什么在 C++ 中 'virtual' 和 '=0' 都需要描述一个方法是抽象的?

C++虚类方法

c++ - C++ 中的抽象类帮助

C++程序在工厂模式中调用父类(super class)方法而不是子类方法

python - 从基类调用派生类中的重写方法

c++ - 在 std::vector 中找不到成员

c++ - Arduino不读取 float 液位开关信号

C++ 在 0(n+m) 复杂度中搜索多个不同长度数组的交集

c++ - 如何在另一个字符串的x位置插入一个字符串?