C++ 重载布尔运算符

0 c++ boolean operator-overloading

我是重载运算符的新手。我正在尝试重载 bool 运算符。我目前使用 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);
}
Run Code Online (Sandbox Code Playgroud)

cig*_*ien 5

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

bool Date::operator==(Date const &d) const
{
    return (mn == d.mn) && (dy == d.dy) && (yr == d.yr);
}
Run Code Online (Sandbox Code Playgroud)

在 class 中Date,声明如下所示:

bool operator==(Date const &d) const;
Run Code Online (Sandbox Code Playgroud)

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

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

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

如果friend在类外定义函数,仍然需要friend在类内将其声明为 a 。但是,定义不能再包含friend关键字。

我还建议更清晰地命名变量一点,如monthdayyear