I am trying to rewrite some example code as a friend function instead of an operator function. I have tried a new declaration in the prototype and beginning of the function. But get an error of
#include <iostream>
usingnamespace std;
// class declaration section
class Date
{
private:
int month;
int day;
int year;
public:
Date(int = 7, int = 4, int = 2005); // constructor
friendbooloperator==(Date &, Date &); // declare the operator== function
};
// class implementation section
Date::Date(int mm, int dd, int yyyy)
{
month = mm;
day = dd;
year = yyyy;
}
booloperator==(&date1, &date2)
{
if(day == date2.day && month == date2.month && year == date2.year)
returntrue;
elsereturnfalse;
}
int main()
{
Date a(4,1,2007), b(12,18,2008), c(4,1,2007); // declare 3 objects
if (a == b)
cout << "Dates a and b are the same." << endl;
else
cout << "Dates a and b are not the same." << endl;
if (a == c)
cout << "Dates a and c are the same." << endl;
else
cout << "Dates a and c are not the same." << endl;
return 0;
}
It seems I've been too slow... :-)
May I humbly add some clarifications about what I think were the errors?
friendbooloperator==(Date &, Date &);
booloperator==(&date1, &date2)
The first declaration of operator==() is correct, but the second isn’t: “&date1” and “&date2” aren’t types, but instances of a type (instances of “Date”).
Also: if(day == date2.day && month == date2.month && year == date2.year)
Once you’ve moved your operator==() outside the declaration of “Date”, it doesn’t have any more a “this”, so it cannot know which “day” or “month” you are referring to: you must always specify that.
Also: operator==() is not supposed to modify your Date(s), so you can pass them to it as constants.
#include <iostream>
usingnamespace std;
// class declaration section
class Date
{
private:
int month;
int day;
int year;
public:
Date(int = 7, int = 4, int = 2005); // constructor
friendbooloperator==(Date &, Date &); // declare the operator== function
};
// class implementation section
Date::Date(int mm, int dd, int yyyy)
{
month = mm;
day = dd;
year = yyyy;
}
booloperator==(Date &date1, Date &date2)
{
if(date1.day == date2.day && date1.month == date2.month && date1.year == date2.year)
returntrue;
elsereturnfalse;
}
int main()
{
Date a(4,1,2007), b(12,18,2008), c(4,1,2007); // declare 3 objects
if (a == b)
cout << "Dates a and b are the same." << endl;
else
cout << "Dates a and b are not the same." << endl;
if (a == c)
cout << "Dates a and c are the same." << endl;
else
cout << "Dates a and c are not the same." << endl;
return 0;
}
Which works a treat. So i have to forgotten to declare the instances of date and compared the days, months and years from date objects that weren't initially referred to.