Global operator functions

I don't completely understand global operator functions. I know that we need them so operations like 5*class_name can work, but is that it? Can we use them on multiple classes?

Since I'm on the topic of operator functions, I have one more question. I saw this example, and all of it makes sense to me except for why there is an & before operator.
1
2
3
4
5
ostream &operator<<(ostream &os, message &m)
{
    os<<m.note;
    return os;
}
Last edited on
Does this make more more sense?

1
2
3
4
5
ostream& operator<<(ostream& os, message& m)
{
    os<<m.note;
    return os;
}
Not quite, could you explain the & at the begining?
You're returning a reference to the ostream object, this is instead of making a copy of the object for the function, which is the only way to pass objects around.
@LowestOne

I have also understood nothing. What is the difference between the original operator function and yours?

1
2
3
4
5
ostream &operator<<(ostream &os, message &m)
{
    os<<m.note;
    return os;
}



1
2
3
4
5
ostream& operator<<(ostream& os, message& m)
{
    os<<m.note;
    return os;
}



@Windwhistles

This is done that you can write for example

cout << m1 << m2;

This is equivalent to

operator <<( operator << ( cout, mq ), m2 );

Last edited on
There is no difference as far as the compiler is concerned. I put the reference with the type because that's what the type is; the operator isn't a reference, and neither is the variable name.

I think ostream &operator could cause more confusion than ostream& operator. Maybe just me?
Topic archived. No new replies allowed.