-1

I am newbie in c++. In the below code example there is a & before operator<< but there is no & before operator==. When should i use & and why? I know this is reference sign but it really hard to understand for me.

class Money {
    int dollars;
    int cents;
public:
    Money(int dollars, int cents);
    Money(int total);

    friend std::ostream &operator<<(std::ostream &os, const Money &rhs);
    bool operator==(const Money &rhs) const;

};


Money::Money(int dollars, int cents) : dollars{dollars}, cents{cents} {}

Money::Money(int total) : dollars {total/100}, cents{total%100}  {}



std::ostream &operator<<(std::ostream &os, const Money &rhs){
    os << "dollars: " << rhs.dollars << " cents: " << rhs.cents;
    return os;
}

bool Money::operator==(const Money &rhs) const{
    if(dollars == rhs.dollars && cents == rhs.cents)
        return true;
    else
        return false;
}


int main(){
    Money money1{3,12};
    Money money2{3,1};

    std::cout << money1 << std::endl;    // dollars: 3 cents: 12

    if(money1==money2)
        std::cout << "These are equal" << std::endl;
    else
        std::cout << "These are not equal" << std::endl;

    return 0;
}
UUser196
  • 25
  • 4
  • 5
    C++ is one of the most complex languages out there to learn. If you are not familiar with what a reference is, then learning operator overloading makes absolutely no sense, to be honest with you. Learning C++ must be done step-by-step, using a book or several books, and not simply getting code from somewhere and trying to figure out the syntax. – PaulMcKenzie Sep 17 '21 at 20:42
  • 1
    A good discussion of operators in general: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading). It's brief and to the point, so it doesn't match up well against a book that will cover everything in depth, but it goes over a lot of ground quickly and put it all in one place. If you read the link and come away thinking "WTF did I just read?" that's a sign that you need a good book. – user4581301 Sep 17 '21 at 20:45

1 Answers1

0

This is a case where more spacing would make this less confusing.

std::ostream & operator<<(std::ostream &os, const Money &rhs){
    os << "dollars: " << rhs.dollars << " cents: " << rhs.cents;
    return os;
}

The return type of the operator<< is std::ostream &. That is, it's returning the os so that you can string a bunch of these things together. operator<< should ALWAYS return the stream you're writing to so you can do:

cout << myObject << " and... " << myOtherObject << endl;

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36