Reputation: 11
I am new to overloading operators. I am trying to overload a bool operator. I am currently using the bool operator as an access function into the Date class. Any suggestions how I would go about converting the bool EqualTo function to overload the operator? Thank you!
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);
}
Upvotes: 0
Views: 2743
Reputation: 60308
The implementation of your EqualTo
function suggests that you should be overloading operator==
to test if 2 Date
objects are equal. All you have to do is rename EqualTo
to operator==
. And you should take the arguments by const&
.
bool Date::operator==(Date const &d) const
{
return (mn == d.mn) && (dy == d.dy) && (yr == d.yr);
}
Inside the class Date
, the declaration would look like:
bool operator==(Date const &d) const;
Another way to do this is to make the operator a friend of the class:
friend bool operator==(Date const &a, Date const &b) const
{
return (a.mn == b.mn) && (a.dy == b.dy) && (a.yr == b.yr);
}
Note that in this case, this is not a member function. In this case, you can define it inside the class (where you need the friend keyword).
If you define a friend
function outside the class, you still need to declare it as a friend
within the class. However, the definition can no longer have the friend
keyword.
I would also recommend naming your variables a bit more clearly, such as month
, day
, and year
.
Upvotes: 5