Search code examples
c++if-statementbooleanoperationboolean-operations

boolean operations overloading inside classes in c++ and if statements for dates inside a class


I'm using this code in my previous question: Adding the year implementation in c++ using a class

I want to use an if statement to check for dates in a way that if the day was 31 it gets back to 0 and the month gets incremented by one. I even tried to write another method and use it inside of the + operation but this failed as well because I'm incrementing the day in the return function inside of the operation declaration. As a result, it will need to be incremented before checking for the conditions first ! but what if the number was initially 31? there is no month that has 32 days !

I tried to use it but because of my implementation it didn't work as it should

My other question is that I'm trying to use a Boolean reference check with the operation == as well

This is what I've done so far :

bool operator==(const Date&) const;

bool Date::operator==(const Date& date) const
{
    if (day == date.day && monthnum == date.monthnum && year == date.year)
        return true;
    else return false;

}

but for some reason when I try to test it in the main by saying for example, date1==date2, it doesn't compile ! am I writing it wrong ?

"no operation == matches these operands" this is the error I get when I try to compile the code


Solution

  • I want to use an if statement to check for dates in a way that if the day was 31 it gets back to 0 and the month gets incremented by one.

    This is as simple to implement as:

    if (day == 31) {
        day = 0;
        monthnum++;
    }
    

    I try to test it in the main by saying for example, date1==date2, it doesn't compile ! am I writing it wrong ?

    Yeah well, you are declaring a free function operator==, while what you want is a member function. Inside Date do:

    class Date {
    public:
        // ...
        bool operator==(const Date&) const;
        // ...
    };
    

    You can also use a free function, to be honest, but that would require more changes and it generally is the same. Just in case you want to use it here's how:

    bool operator==(const Date& lhs, const Date& rhs) {
        return (lhs.day == rhs.day && lhs.monthnum == rhs.monthnum && lhs.year == rhs.year);
    }
    

    (I've removed the redundant if-else pair).


    The compiler states that "no operation == matches these operands". I simply have this code in my main: cout << date1 == date2;

    Yes, you should do this instead:

    cout << (date1 == date2);
    

    otherwise what the compiler reads is this:

    (cout << date1) == date2;