I try to overload the operator<<
, but there is a warning that I cannot overload it. I can overload this operator as follows:
std::cout << test4 << std::endl;
But I can not overload it as follows:
std::cout << test2 + test3 << std::endl;
My main code is:
Stonewt test2(2, 8, Stonewt::STONE);
std::cout << "test2: " << test2 << std::endl;
Stonewt test3(2, 3, Stonewt::POUNDS);
std::cout << "test3: " << test3 << std::endl;
Stonewt test4 = test2 + test3;
std::cout << test4 << std::endl; // operator << can overload
std::cout << test2 + test3 << std::endl; // operator << cannot overload
Below is the friend
function
std::ostream& operator <<(std::ostream& os, Stonewt& a)
{
if (a.format == Stonewt::STONE)
{
os << "stone format" << '\n';
os << a.stone << " stones " << a.pound << " pounds" << '\n';
}
else if (a.format == Stonewt::POUNDS)
{
os << "pounds format" << '\n';
os << a.pounds << " pounds" << '\n';
}
else
os << "not valdid" << '\n';
return os;
}
The test2+test3
results a temporary Stonewt
object(rvalue) which can not be bound to a non-const
reference(lvalue: i.e. Stonewt &a
),rather with a const
qualified lvalue reference. Therefore change the non-member function to:
std::ostream & operator <<(std::ostream &os, const Stonewt &a)
// ^^^^^^^^^^^^^^^^
{
// ....
return os;
}
Further readings: