如果从同一基类相互作用的两个不同的派生类对象,如何提出异常?
我有一个带有A&的抽象基类(x) B派生的类。
我在X中有一个类方法,该方法由两个类A& B.
我希望该方法能够引发异常,如果两个不同的派生类对象相互交互。
这是一个人为的例子:
class Food{
public:
int count;
void combine(Food* a) {
this->count += a->count;
}
};
class Orange : Food {
public:
Orange(int x) {
count = x;
}
};
class Apple : Food{
public:
Apple(int x) {
count = x;
}
};
int main() {
Food* basket_apples = new Apple(5);
Food* basket_oranges = new Orange(4);
Food* crate_oranges = new Orange(10);
crate_oranges.combine(basket_oranges);//should work fine
crate_oranges.combine(basket_apples); //should produce error
}
我考虑的解决方案是覆盖两个派生类中的联合方法,但这违反了干燥(不要重复自己)。
我想知道是否还有其他选择可以解决此问题。
I have an abstract base class(X) with A & B derived classes.
I have a class method in X that is inherited by both classes A & B.
I want the method to be able to throw an exception if two different derived class objects interact with each other.
Here is a contrived example:
class Food{
public:
int count;
void combine(Food* a) {
this->count += a->count;
}
};
class Orange : Food {
public:
Orange(int x) {
count = x;
}
};
class Apple : Food{
public:
Apple(int x) {
count = x;
}
};
int main() {
Food* basket_apples = new Apple(5);
Food* basket_oranges = new Orange(4);
Food* crate_oranges = new Orange(10);
crate_oranges.combine(basket_oranges);//should work fine
crate_oranges.combine(basket_apples); //should produce error
}
A solution I considered is to override the combine method in both derived classes but that violates DRY(Don't repeat yourself).
I want to know if there are any other options to solve this issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在组合函数中检查一下:
如果要管理错误,使用异常或返回值:
也许您应该转移计数器?
注意:如用户17732522所说,您的成员函数
组合
应该是虚拟的,并且类应该更好地管理继承。我建议这样做:You can check that in the combine function :
If you want to manage the error, use exception or return value :
Maybe you should transfert the counter ?
Note: As said by user17732522, your member function
combine
should be virtual and the class should better manage the inheritence. I suggest this :