xampla
xampla

Reputation: 159

Defining the operator < in a class for a map (c++)

So I have a class:

class Time{
    private:
    string day;
    string hour;
    public:
    //etc
    }

I've defined in the class:

bool Time::operator <(const Time &t1) const {
     if (day!= t1.see_day()) {
        return day < t1.see_day();
     }
     else return hour < t1.see_hour;
}

When I compile it gives me an error:

"error passing 'const Time' as 'this' argument of std::string Time::see_day()" discards qualifiers[-fpermissive].

I want this just for creating an iterator to write all the map in an ascending order. What am I doing wrong?

Upvotes: 0

Views: 39

Answers (1)

vsoftco
vsoftco

Reputation: 56547

You need to mark your

Time::see_day() const
//              ^^^^^
//             needs to be const

as otherwise in the line

return day < t1.see_day();

you try to invoke a non-const member function on a const instance (t1 in this case), and that is forbidden, hence the error.

Same issue with Time::see_hour() (you also have a typo, missing parentheses for the function call).

Upvotes: 5

Related Questions