Thread: Overloading the < Operator

  1. #1
    Registered User
    Join Date
    May 2007
    Location
    Melb Australia
    Posts
    7

    Overloading the < Operator

    I've been trying to overload the operator, so I can use a class for a priority_queue, thus far i have:

    Code:
    In function `bool operator<(const Thread&, const Thread&)':
    71: passing `const Thread' as `this' argument of `int Thread::getreq()'
       discards qualifiers
    71: passing `const Thread' as `this' argument of `int Thread::getreq()'
       discards qualifiers
    and my attempt at overloading is:

    Code:
    bool operator<(const Thread &a, const Thread &b)
    {
       bool result = a.getreq() < b.getreq();
       return result;
    }
    Now, checking out the other threads on here, there were one or two that were similar to what was going on with my stuff, but it seems that what worked for others, didn't really do anyhting for me

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You need to make the getreq function const by adding the keyword const after the parameter list parentheses, e.g.
    Code:
    int getreq() const;
    That tells the compiler that the function won't change the state of the object, which is what the compiler needs to know before it allows you to call it from a const object (or a reference to a const object).

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Make sure your operator < is also declared as a static or friend function, since you're using the two-parameter form (which btw is the preferred method).
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Actually, in this case a plain, non-member function should be fine. No need for static or friend.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. unary operator overloading and classes
    By coletek in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2009, 02:14 AM
  2. Overloading == and < operator
    By cannsyl in forum C++ Programming
    Replies: 3
    Last Post: 11-23-2008, 10:21 PM
  3. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  4. Operator Overloading (Bug, or error in code?)
    By QuietWhistler in forum C++ Programming
    Replies: 2
    Last Post: 01-25-2006, 08:38 AM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM