![](/img/trans.png)
[英]How can I call methods of inherited classes just by calling the same method of base class?
[英]how can I use an inherited method and the same base class method?
假設我有一只動物和一只繼承動物的狗。 假設我想調用一個特定於dog的名為“ eat()”的方法,但是所有動物之間都有一些共享的eat代碼,因此我知道我可以將“ eat()”虛擬化,但是它不會使用基類代碼,例如,我是否應該僅將基類稱為“ eatAll()”,然后來自特定動物的每個eat方法都必須調用它? 我只是在尋找最佳設計。 這是在C ++中
這是經典的模板方法模式 。 基本上:
class Animal
{
void Eat()
{
//stuff specific to all animals
SpecificEat();
}
virtual void SpecificEat() = 0;
};
class Dog : Animal
{
virtual void SpecificEat()
{
//stuff specific to dog
}
};
使用這種方法,您不必在派生類的替代中顯式調用基類方法。 它由非virtual
Eat()
自動調用,並且特定功能由virtual SpecificEat()
。
我建議您的基類接口具有掛鈎,以調用派生類型的特定功能。 這稱為模板方法模式。 這是一個例子:
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";
}
};
只需調用基類的方法即可。
class Dog : public Animal
{
public :
void Eat()
{
// .. MAGIC
Animal::Eat();
}
};
請注意,如果Animal類的Eat
方法是純虛擬的(我對此表示懷疑),則不會鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.