【发布时间】:2016-09-23 15:05:03
【问题描述】:
我有多个,比如 2 个,派生自抽象基类的类,比如 Ingredient。现在,Carrot 和Potato 通过公共继承实现了Ingredient 的纯虚函数(称为Taste())。现在,假设我想要一个类Salt,它是一个Ingredient(即它派生自它),但需要调用其姐妹类的Taste() 实现?
基本上,Salt 类稍微修改了其姐妹类的 Taste() 实现。
这可以实施吗?如果有,怎么做?
这是我想做的事情的草图:
class Ingredient {
virtual void Taste() = 0;
};
class Carrot : public Ingredient {
void Taste() { printf("Tastes like carrot");}
};
class Potato : public Ingredient {
void Taste() { printf("Tastes like potato"); }
};
class Salt : public Ingredient {
void Taste() { SisterClass->Taste(); printf(" but salty"); }
};
【问题讨论】:
-
你想如何获取使用哪个
SisterClass? -
@PcAF 我认为指针将是理想的,就像@Quentin 答案中的组合方法一样。我考虑过使用模板对
Salt中的Sister类进行参数化,但我不确定这是否是最好的方法。