为什么 test2 + test3 的运算符<<不能过载?

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

本文关键字:lt 不能 test2 运算符 为什么 test3      更新时间:2023-10-16

我尝试重载operator<<,但有一个警告说我不能重载它。我可以按如下方式重载此运算符:

std::cout << test4 << std::endl;

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

std::cout << test2 + test3 << std::endl;

我的主要代码是:

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

以下是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;
}

test2+test3结果是一个临时Stonewt对象(rvalue(,它不能绑定到non-const引用(lvalue:即Stonewt &a(,而是使用const合格的左值参考。因此,将非成员函数更改为:

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

延伸阅读:

  • 为什么不能传递临时对象作为引用?
  • 为什么临时对象可以绑定到常量引用?
  • 为什么非常量引用不能绑定到临时对象?

这不是运算符<<不适用于test2 + test3。它缺少运算符+。

您需要重载运算符+,以便"test2 + test3"将起作用。运算符<<的重载正在工作,但编译器在遇到"test2 + test3"时不知道该怎么做,从而发出假定的错误。