我有一个看起来像这样的类:
class Player
{
friend bool operator>=(Player &pl1, Player &pl2)
{
return true;
};
private:
int nr, height, weight;
}
球员有号码、高度和体重。 现在我想知道 Player1 是否比 Player2 更大和/或更重。在此之后我想像这样打印出来:
Player A is 2 cm bigger (smaller) and 7 kg heavier (lighter) than Player B.
只能返回true或false怎么管理?当他更大更重时我可以返回 true 或者当他更小更轻时我可以返回 false,但是我应该如何管理更大/更轻 |更小/更重的情况?
编辑:我必须使用 operator>=
来完成它。这是我学校的考试,条件是这样。正文如下:
After the input the players will be displayed. By using operator overloading >= will be checked if the player is bigger and/or heavier than the other player. The result with the determined data will be displayed, e.g.: Player A is 2 cm bigger (smaller) and 7 kg heavier (lighter) than Player B.
最佳答案
如果您的类不存在严格的排序,请不要定义排序运算符。
相反,您可以编写像 heightDifference
和 weightDifference
这样的函数:
int heightDifference (const Player& a, const Player& b)
{
return a.height - b.height;
}
然后您可以使用这些函数计算出您需要的信息。
关于C++ 运算符重载 >= 有 2 个不同的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868616/