C++ overload bool operator

问题描述 投票:0回答:1

我是一个新的超载操作符。我正在尝试重载一个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);
}
c++ boolean operator-overloading
1个回答
5
投票

实现你的 EqualTo 函数表明,你应该超载 operator== 检验是否为2 Date 对象是平等的。您所要做的就是重命名 EqualTooperator==. 而你应该采取的论点是 const&.

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

班级内部 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 关键字。

我还建议将你的变量命名得更清楚一些,比如说 month, dayyear.

© www.soinside.com 2019 - 2024. All rights reserved.