当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to implement an equality operator function for a proxy class

问题描述:

I have a class Date that I defined that models a date, it has a day,month and a year as data members. Now to compare the dates I created the equality operator

bool Date::operator==(const Date&rhs)

{

return (rhs.day()==_day && _month==rhs.month() &&_year==rhs.year());

}

Now how do I call the Date class equality operator from the Proxy class...??


This is the edited part of the question

This is the Date Class

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

This is the proxy class that I will substitute for the Date class

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

Now the problem that I am having is implementing the equality operator function in the proxy class, I hope this clarifies the question.

网友答案:
return *_datePtr == *_rhs.datePtr;
网友答案:

Well, just use the operator:

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

Notice how the operator== takes a reference. That means, if you have a pointer (or an object acting like a pointer such as scoped_ptr or shared_ptr), then you have to dereference it first:

*_datePtr == *rhs._datePtr;

By the way, you should read this: Operator overloading.

网友答案:

It should work like any other equality operator if it is implemented correctly.

Try:

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");
分享给朋友:
您可能感兴趣的文章:
随机阅读: