错误:无法绑定&#39; std :: ostream {aka std :: basic_ostream <char>}

时间:2015-05-11 21:49:57

标签: c++ c++11 stl

我搜索了一些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

1 个答案:

答案 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";
}
相关问题