2011-11-13 76 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"); 
相關問題