运算符<<使用temp变量工作,但不直接使用函数调用
operator<< working w/ temp variable, but not directly with function call
我正在尝试为一个类编写一个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&
,可以向其转换右值。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销