Search code examples
c++operator-keyword

C++ Must take either one or zero argument error (Operator+)


I have the following statement in my Hour.cpp file: (after class Hour)

Hour Hour ::operator+(const Hour& h1, const Hour& h2) const{
    return Hour(h1.getHour()+ h2.getHour(), h1.getMinute() + h2.getMinute(), h1.getSecond() + h2.getSecond());
}

However, after running it I get:

error:  must take either zero or one argument

Solution

  • While overloading an operator as a member function, you can only another class as a second operand. The first operand is the object of the class itself. So, you have two options:

    • You can modify the overloading function as
    Hour Hour::operator+(const Hour& h) const{
        return Hour(hour_ + h.getHour(), minute_ + h.getMinute(), seconds_ + h.getSecond());
    }
    
    where hour_, minute_, seconds_ are member variables of Hour class.
    
    • Do not implement as a member function
    Hour operator+(const Hour& h1, const Hour& h2) const{
        return Hour(h1.getHour()+ h2.getHour(), h1.getMinute() + h2.getMinute(), h1.getSecond() + h2.getSecond());
    }