Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator overloading<< error

Im trying to overload the operator<<

const ostream & operator<<(const ostream& out, const animal& rhs){
    out << rhs.a;
    return out;
}

it seems that im getting an error because im return a const and also because the first argument is const refrence to an ostream object.

cout << objectOfAnimal1 << objectOfAnimal2 ;

it work just fine if I change the the return type and the operator signature to this one:

ostream & operator<<(ostream& out, const animal& rhs)
like image 833
AlexDan Avatar asked May 25 '26 16:05

AlexDan


2 Answers

You need to have:

ostream & operator<<(ostream& out, const animal& rhs)

In your code You are trying to modify a const ostream object, and so you get the errors.
It should not be const.

like image 126
Alok Save Avatar answered May 28 '26 05:05

Alok Save


ostream & operator<<(ostream& out, const animal& rhs){
out << rhs.a;
return out;
}

You've already explained what is probable reason of problem and you really didn't try it out?

like image 43
Griwes Avatar answered May 28 '26 05:05

Griwes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!