我搜索了一些Q但我无法找到答案。
我想要重载operator<<
,但它对我不起作用。
#include <iostream>
#include <string>
#include <tuple>
class Foo
{
public:
std::tuple<int, float> tp;
Foo(int _a, float _b)
{
std::get<0>(tp)=_a;
std::get<1>(tp) =_b;
}
friend std::ostream& operator<<(std::ostream & strm, const std::tuple<int, float> &tp)
{
strm << "[ "<<std::get<1>(tp)<<", "<<std::get<0>(tp)<<"]"<<"\n";
return strm;
}
};
int main ()
{
Foo a(1, 3.0f);
std::cout<<a;
return 0;
}
错误:
cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
std::cout<<a;
^
更新 解决了,谢谢@juanchopanza
答案 0 :(得分:3)
为了调用std::cout<<a;
,您需要重载具有Foo
作为第二个参数的输出流运算符。例如:
friend
std::ostream& operator<<(std::ostream& strm, const Foo& foo)
{
return strm << "[ " << std::get<1>(foo.tp) << ", "
<< std::get<0>(foo.tp) << "]" << "\n";
}