Operator overload << error

Im trying to overload the operator <<

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

it seems im getting an error because im returns a constant, and also because the first argument is const refrence for the ostream object.

cout << objectOfAnimal1 << objectOfAnimal2 ;

It works fine if I change the return type and the operator signature to this:

ostream & operator<<(ostream& out, const animal& rhs)
+3
source share
2 answers

You need:

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

In the code, you are trying to modify the object const ostreamand you will get errors.
It should not be const.

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

You have already explained what is the probable cause of the problem, and you really have not tried it?

+1
source

All Articles