[英]how can I use an inherited method and the same base class method?
let's say I have a class animal and a class dog that inherits animal. 假设我有一只动物和一只继承动物的狗。 Let's say I want to call a method called 'eat()' that is specific to dog but there is some shared eat code between all animals, so I know I can make 'eat()' virtual but then it won't use the base class code, should I just call my base class 'eatAll()', for example, and then every eat method from a specific animal will have to call that?
假设我想调用一个特定于dog的名为“ eat()”的方法,但是所有动物之间都有一些共享的eat代码,因此我知道我可以将“ eat()”虚拟化,但是它不会使用基类代码,例如,我是否应该仅将基类称为“ eatAll()”,然后来自特定动物的每个eat方法都必须调用它? Just looking for the best design I guess.
我只是在寻找最佳设计。 This is in c++
这是在C ++中
This is classic template method pattern . 这是经典的模板方法模式 。 Basically:
基本上:
class Animal
{
void Eat()
{
//stuff specific to all animals
SpecificEat();
}
virtual void SpecificEat() = 0;
};
class Dog : Animal
{
virtual void SpecificEat()
{
//stuff specific to dog
}
};
Using this approach, you don't have to explicitly call the base class method in derived classes' overrides. 使用这种方法,您不必在派生类的替代中显式调用基类方法。 It's called automatically by the non-
virtual
Eat()
and the specific functionality is implemented by virtual SpecificEat()
. 它由非
virtual
Eat()
自动调用,并且特定功能由virtual SpecificEat()
。
I would suggest that your base class interface have hooks to call into specific functionality of derived types. 我建议您的基类接口具有挂钩,以调用派生类型的特定功能。 This is called the template method pattern.
这称为模板方法模式。 Here's an example:
这是一个例子:
class Animal
{
public:
void eat()
{
std::cout << "Mmmm... It's ";
do_eat();
}
private:
virtual void do_eat() = 0;
};
class Dog
: public Animal
{
virtual void do_eat()
{
std::cout << "Dog Food!\n";
}
};
class Human
: public Animal
{
virtual void do_eat()
{
std::cout << "Pizza!\n";
}
};
Just call the base class' method. 只需调用基类的方法即可。
class Dog : public Animal
{
public :
void Eat()
{
// .. MAGIC
Animal::Eat();
}
};
Note that if your Animal class's Eat
method is pure virtual (which I doubt), this will not link. 请注意,如果Animal类的
Eat
方法是纯虚拟的(我对此表示怀疑),则不会链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.