Thread: operator overloading question

  1. #1
    Registered User brianptodd's Avatar
    Join Date
    Oct 2002
    Posts
    66

    operator overloading question

    I am writing a clock class and am working on the operator overloading to compare two clocks, but my compiler is telling me:

    "bool operator < (const Clock& c1, const Clock& c2) must take exactly one argument"

    Does anyone know why?
    "In theory, there is no difference between theory and practice. But, in practice, there is."
    - Jan L.A. van de Snepscheut

  2. #2
    cgoat
    Guest
    For a member variable:

    Code:
    class Clock
    {
    public:
       bool operator<(const Clock &rhs);
    
    private:
       unsigned long m_time;
    };
    
    bool Clock::operator<(const Clock &rhs)
    {
       if(rhs.m_time <= m_time) return false;
       return true;
    }
    For a global function:

    Code:
    class Clock
    {
    public:
       friend bool operator<(const Clock &lhs, const Clock &rhs);
    
    private:
       unsigned long m_time;
    };
    
    bool operator<(const Clock &lhs, const Clock &rhs)
    {
       if(rhs.m_time <= lhs.m_time) return false;
       return true;
    }
    Either of those should work, but I didn't actually test them so if it doesn't post the error message.

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    596
    Does anyone know why?
    When you overload, you can change what the operator does, but you can't change its syntax. So the < operator always takes two operands, overloaded or not. But when you overload it as a member function, the class object to which it belongs is implicitly the first operand, so the function can only take one operand as a parameter.

    On the other hand, if you overload it as a top-level function, you have to provide two operands as parameters.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM