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!
The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)
assertEquals is calling the equals(Object obj) method of the super class (in your case Object) which by default just compares the reference of the object. As they are not the same object your result will fail. So if you look at it as the interpreter sees it. And return this.
Compare two objects in C++ We can determine whether two objects are the same by implementing a comparison operator== for the class. For instance, the following code compares two objects of class Node based on the value of x and y field.
Comparing Objects ¶ When using the comparison operator ( == ), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with == ), and are instances of the same class.
into the class's public
area
bool operator==(const Date& rhs) const {
return
year == rhs.year
&& month == rhs.month
&& day == rhs.day
;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With