我有一個帶有 A 和 B 派生類的抽象基類(X)。
我在 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
}
我考慮的一個解決方案是在兩個派生類中重寫 combine 方法,但這違反了 DRY(不要重復自己)。
我想知道是否有任何其他選項可以解決此問題。
uj5u.com熱心網友回復:
您可以在組合功能中檢查:
void combine(Food const& a) // You should pass your argument by const ref
{
assert(typeid(*this) == typeid(a)); // This checks ONLY IN DEBUG !
this->count = a.count;
}
如果要管理錯誤,請使用例外或回傳值:
void combine(Food const& a)
{
if(typeid(*this) != typeid(a))
throw std::runtime_error("Invalid combined types");
this->count = a.count;
}
int combine(Food const& a)
{
if(typeid(*this) != typeid(a))
return 1;
this->count = a.count;
return 0;
}
也許你應該轉移柜臺?
void combine(Food& a) // Passing by non-const reference
{
assert(typeid(*this) == typeid(a));
this->count = a.count;
a.count = 0;
}
注意:正如 user17732522 所說,您的成員函式combine應該是虛擬的,并且類應該更好地管理繼承。我建議這樣做:
class Food
{
protected:
std::size_t count; // You want this value >= 0
public:
Food(std::size_t count_) : count(count_) {}
Food(Food const& f) : count(f.count) {}
virtual ~Food() {}
virtual std::string name() const = 0;
virtual void combine(Food const& a)
{
assert(typeid(a) == typeid(*this));
this->count = a.count;
}
};
class Orange : public Food
{
public:
Orange(std::size_t x) : Food(x) {}
Orange(Orange const& o) : Food(o) {}
virtual ~Orange() {}
virtual std::string name() const { return "orange"; }
};
class Apple : public Food
{
public:
Apple(std::size_t x) : Food(x) {}
Apple(Apple const& a) : Food(a) {}
virtual ~Apple() {}
virtual std::string name() const { return "apple"; }
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465275.html
