C++ 运算符重载 >= 有 2 个不同的返回值

标签 c++ return operator-overloading

我有一个看起来像这样的类:

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.

最佳答案

如果您的类不存在严格的排序,请不要定义排序运算符。

相反,您可以编写像 heightDifferenceweightDifference 这样的函数:

int heightDifference (const Player& a, const Player& b)
{
    return a.height - b.height;
}

然后您可以使用这些函数计算出您需要的信息。

关于C++ 运算符重载 >= 有 2 个不同的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868616/

相关文章:

c - c中的数组返回错误

C++:重载 [ ] 运算符以进行读写访问

c++ - 如何重载 == 运算符以允许它用于多重比较?

c++ - 如何在仅 header 模式下使用 fmt 库?

堆栈上的 C++ 编程书籍示例

C++如何从函数返回和收集地址

c++ - 构建前缀运算符

c++ - 帮助解决错误 : ISO C++ forbids declaration of 'vector' with no type

c++ - 查找字符串 1 包含字符串 2 C++ 的次数的函数

c - 堆栈弹出/推送段错误错误的相同数字