如何为代理类实现相等操作符函数

How to implement an equality operator function for a proxy class

本文关键字:操作符 函数 实现 代理      更新时间:2023-10-16

我定义了一个类Date来建模一个日期,它有一个日、一个月和一个年作为数据成员。现在为了比较日期,我创建了相等运算符

bool Date::operator==(const Date&rhs)
{
    return (rhs.day()==_day && _month==rhs.month() &&_year==rhs.year());
}

现在我如何从代理类调用日期类相等操作符…??


这是问题的编辑部分

这是日期类

//Main Date Class
enum Month 
{
    January = 1, 
    February,
    March, 
    April,
    May,
    June,
    July, 
    August, 
    September,
    October,
    November, 
    December
};
class Date
{
public: 
    //Default Constructor
    Date();
    // return the day of the month
    int day() const
    {return _day;}
    // return the month of the year
    Month month() const
    {return static_cast<Month>(_month);}
    // return the year
    int year() const
    {return _year;}
    bool Date::operator==(const Date&rhs)
    {
    return (rhs.day()==_day && _month==rhs.month() &&_year==rhs.year());
    }
    ~Date();
private:
    int _day;
    int _month;
    int _year;
}
//--END OF DATE main class

这是我要替换Date类的代理类

//--Proxy Class for Date Class
class DateProxy
{
public: 
    //Default Constructor
    DateProxy():_datePtr(new Date)
    {}
    // return the day of the month
    int day() const
    {return _datePtr->day();}
    // return the month of the year
    Month month() const
    {return static_cast<Month>(_datePtr->month());}
    // return the year
    int year() const
    {return _datePtr->year();}
    bool DateProxy::operator==(DateProxy&rhs)
    {
        //what do I return here??
    }
    ~DateProxy();
private:
    scoped_ptr<Date> _datePtr;
}
//--End of Proxy Class(for Date Class)

现在我遇到的问题是在代理类中实现相等运算符函数,我希望这能澄清问题。

那就用运算符:

Date d1, d2;
if(d1 == d2)
    // ...

注意operator==是如何接受引用的。这意味着,如果你有一个指针(或一个像指针一样的对象,如scoped_ptrshared_ptr),那么你必须首先取消对它的引用:

*_datePtr == *rhs._datePtr;

顺便说一下,你应该读一下:操作符重载

return *_datePtr == *_rhs.datePtr;

如果正确实现,它应该像任何其他相等操作符一样工作。

试题:

Date a = //date construction;
Data b = //date construction;
if(a == b)
    printf("a and b are equivalent");
else
    printf("a and b are not equivalent");