运算符<<使用temp变量工作,但不直接使用函数调用

operator<< working w/ temp variable, but not directly with function call

本文关键字:lt 函数调用 工作 temp 使用 变量 运算符      更新时间:2023-10-16

我正在尝试为一个类编写一个std::ostream operator<<。 我有一个函数(利用 ROV)返回该类的实例。

当我将该函数调用的结果分配给局部变量,然后将局部变量传递给operator <<时,我的运算符起作用,但当我直接传入结果时则不工作。 这是怎么回事?

简化的独立示例(测试.cpp):

#include <iostream>
template <class T>
class AnObject{
public: 
  AnObject(T value) : m_value(value) {}
  T getValue(){ return m_value; }
protected:
  T m_value;
};
template <class T>
std::ostream & operator<<(std::ostream& os, AnObject<T> & obj )
{
  os << obj.getValue();
  return os;
}
AnObject<int> getObject()
{
  return AnObject<int>(5);
}
int main(int argc, char**argv)
{
  // This doesn't compile
  std::cout << getObject() << std::endl;
  // This does....
  //auto obj = getObject();
  //std::cout << obj << std::endl;
}

编译器命令(Ubuntu 上的 g++ 版本 4.8.4):

g++ -std=c++11 test.cpp

错误:

test.cpp:26:26: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
AnObject<int> getObject()
{
  return AnObject<int>(5);
}

上面的这个函数是你的错误。为什么?因为它用作右值表达式的一部分,而右值表达式不是左值。

在C++中,lvalues表示保存实际值的"容器"。 rvalues指的是这些"实际"值。一个很好的例子:

int i = 5; // i is the lvalue, 5 is the rvalue.
// 5 by itself is not a variable, but i has the rvalue of 5 but the lvalue of i.

<<运算符想要一个实际的对象而不是它的值——换句话说,它应该有一个"家"并存储在某个地方。

因此,要么进行另一个需要&&的重载,这意味着它可以采用可能不会在任何地方"存在"的值(例如表达式),或者要求输入的值是左值(对真实对象的引用)。一个不错的选择是使用 const T& ,可以向其转换右值。