首页 > 解决方案 > C++ 重载布尔运算符

问题描述

我是重载运算符的新手。我正在尝试重载布尔运算符。我目前正在使用 bool 运算符作为 Date 类的访问函数。有什么建议我将如何将 bool EqualTo 函数转换为重载运算符?谢谢!

class Date {
private:
    int mn;        //month component of a date
    int dy;        //day component of a date
    int yr;        //year comonent of a date

public:
    //constructors
    Date() : mn(0), dy(0), yr(0)
    {}
    Date(int m, int d, int y) : mn(m), dy(d), yr(y)
    {}

    //access functions

    int getDay() const
    {
        return dy;
    }
    int getMonth() const
    {
        return mn;
    }
    int getYear() const
    {
        return yr;
    }

    bool EqualTo(Date d) const;

};

bool Date::EqualTo(Date d) const
{
    return (mn == d.mn) && (dy == d.dy) && (yr == d.yr);
}

标签: c++booleanoperator-overloading

解决方案


您的函数的实现EqualTo表明您应该重载operator==以测试 2 个Date对象是否相等。您所要做的就是重命名EqualTooperator==. 你应该通过const&.

bool Date::operator==(Date const &d) const
{
    return (mn == d.mn) && (dy == d.dy) && (yr == d.yr);
}

在 class 内部Date,声明如下所示:

bool operator==(Date const &d) const;

另一种方法是让操作符成为类的朋友:

friend bool operator==(Date const &a, Date const &b) const
{
    return (a.mn == b.mn) && (a.dy == b.dy) && (a.yr == b.yr);
}

请注意,在这种情况下,这不是成员函数。在这种情况下,您可以在类中定义它(您需要friend关键字)。

如果你friend在类外定义了一个函数,你仍然需要friend在类内声明它。但是,定义不能再有friend关键字。

我还建议您更清楚地命名变量,例如month,dayyear.


推荐阅读