vendredi 9 août 2019

Why can not the operator<< for test2 + test3 be overloaded?

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;
}

Aucun commentaire:

Enregistrer un commentaire