I am writing a “Date” class for an assignment and I am having trouble doing one the of the functions.
This is the header file for the class.
class Date
{
public:
Date(); // Constructor without parameters
Date(int m, int d, int y); // Constructor with parameters.
// accessors
int GetMonth(); // returns the size of the diamond
int GetDay();
int GetYear();
// mutators
bool Set(int m, int d, int y);
bool SetFormat(char f);
// standard input and output routines
void Input();
void Show();
void Increment(int numDays = 1);
int Compare(const Date& d);
private:
int month, // month variables
day, // day variable
year; // year variable
char format;
};
The member function I am trying to make is the int Compare(const Date& d) function. I need this function to compare two Date objects (the calling object and the
parameter), and should return: -1 if the calling object comes first
chronologically, 0 if the objects are the same date, and 1 if the parameter object
comes first chronologically.
I have tried doing a simple if statement with the == operator but I get errors.
if (d1 == d2)
cout << "The dates are the same";
return (0);
After the objects are created, the function should be called like this d1.Compare(d2)
Thank you in advance!
Usually, you’lll also want to provide overloaded comparison operators, for example (also within the class definition):
PS: There are smarter implementations of
Compare()– just check the other answers. This one is pretty straightforward and readable, but conforms exactly to your specification.