2011-11-13 99 views
0

我有一个类我定义的日期模型是一个日期,它具有一个日期,月份和年份作为数据成员。现在来比较我创建的相等运算符的日期。如何为代理类实现相等运算符函数

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

现在我该如何从Proxy类中调用Date类相等运算符...?


这是问题

这为编辑部分是Date类

//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) 

现在我遇到的问题是在代理类中实现相等运算符函数,I hop这澄清了这个问题。

+3

的代理类?我没有在你的问题中看到任何...无论如何,你的代理类肯定会持有一个指向类'Date'的指针或引用,对吧?那么比较那些引用日期的问题在哪里? – celtschk

回答

2
return *_datePtr == *_rhs.datePtr; 
3

好了,只需要使用操作:

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

注意的operator==是如何发生的参考。这意味着,如果你有一个指针(或物体像个指针如scoped_ptrshared_ptr),那么你必须取消对它的引用第一:

*_datePtr == *rhs._datePtr; 

顺便说一句,你应该阅读:Operator overloading

0

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

尝试:

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"); 
相关问题