【发布时间】:2021-10-07 22:27:35
【问题描述】:
class Media {
public:
bool operator==(const Media& other) const {}
bool operator!=(const Media& other) const {}
};
class Book : public Media {
public:
bool operator==(const Book& other) const {} // commenting out this line solves this issue.
bool operator!=(const Book& other) const {}
};
class Game : public Media {
public:
bool operator==(const Game& other) const {}
bool operator!=(const Game& other) const {}
};
int main() {
Book book;
Game game;
bool res = book == game; // doesn't compile.
}
我有这 3 个类,它们必须定义自己的 == 和 != 运算符。但是我还必须使用这些运算符比较两个兄弟姐妹。
我本可以在子类覆盖的基类中编写一个(纯)虚函数,例如virtual bool equals(const Media& other) const。然后在基类Media 中的== 和!= 操作符定义中调用该函数。但是,当我在 Book 类中添加另一个 bool operator==(const Book& other) const {} 时,该功能就消失了(Game 类也是如此)。
现在我想使用这些运算符比较兄弟姐妹之间的比较,并且在这 3 个类中仍然有所有 6 个定义。如何让它发挥作用?
【问题讨论】:
-
比较
Book和Game时是否要使用Media::operator==(const Media&)运算符? -
您有 3*3 个组合(用于
==),您的预期结果是什么? -
如果以这种方式具有可比性,则应在 Media 类上进行比较。我的意思是,如果您将它们纯粹视为媒体,那么您应该能够比较它们,因此只需实现 Media == 和 != 运算符。
-
我认为最重要的问题是为什么你想像这样比较不同的类型?如果不同的媒体应该是对称平等的,那么应该可以仅根据基类对信息的了解进行比较——而不是孩子。如果你把自己设计到了一个只有这样出路的角落,那么这种设计存在问题的味道很浓。
标签: c++ oop polymorphism operator-overloading overloading