Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

overloading operators in c++?

is this correct way to do it?

class Time

{

public:

bool Time::operator ==(const Time &other) const

friend std::ostream& operator<<(ostream&, Time&);

private:

int hour;

int minute;

};

bool Time::operator==(const Time &other) const {

return !(*this == other);

}

ostream& operator<<(ostream &out, Time &ob) {

out << “Time : ”<<ob.hour << ob.minute<<endl;

return out; }

Update:

there isnt suppose to be a ! in the return statement...

2 Answers

Relevance
  • oops
    Lv 6
    1 decade ago
    Favorite Answer

    Close. You've got the signature right, but you've defined the function in terms of itself. This expression:

    *this == other

    Is calling operator== of the the Time class. So what you've actually done there is create a recursive function with no terminating condition. What you want to do is this:

    bool Time::operator==(const Time &other) const {

        return ((hour == other.hour) && (minute == other.minute));

    }

    Your output operator will work, but the Time object should be const.

    Lastly, in your class body, you don't need to prefix your operator function with "Time::", you can just write it like this:

    bool operator ==(const Time &other) const;

  • 4 years ago

    Operator overloading is under polymorphism a particular function in C++. together as the operators in C have nicely-known meaning operator overloading in C++ enables us to overload the operator to offer the specific consumer defined function to the operator. Syntax is going like this operator x(arguments) { function } the place x is an operator operator overloading is as a rule used to function the products making use of operators quite of working their contributors.

Still have questions? Get your answers by asking now.