为什么运算符<<对于test2 + test3不能超载?

Zhi*_*ang 2 c++ class operator-overloading friend-function c++11

我尝试重载operator<<,但有警告我无法重载。我可以按如下方式重载该运算符:

std::cout << test4 << std::endl;
Run Code Online (Sandbox Code Playgroud)

但是我不能按如下方式重载它:

std::cout << test2 + test3 << std::endl;
Run Code Online (Sandbox Code Playgroud)

我的主要代码是:

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
Run Code Online (Sandbox Code Playgroud)

下面是friend功能

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;
}
Run Code Online (Sandbox Code Playgroud)

JeJ*_*eJo 5

test2+test3结果的临时Stonewt对象(右值不能被绑定到)non-const参考(左值:即Stonewt &a),而具有const合格的左值参考。因此,将非成员函数更改为:

std::ostream & operator <<(std::ostream &os, const Stonewt &a)
//                                           ^^^^^^^^^^^^^^^^
{
      // ....
      return os;
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读: