c++ - 错误:无法绑定(bind) 'std::ostream {aka std::basic_ostream<char>}

标签 c++ c++11 stl

我搜索了一些问题,但找不到答案。

我想要重载 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

最佳答案

为了调用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";
}

关于c++ - 错误:无法绑定(bind) 'std::ostream {aka std::basic_ostream<char>},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30178224/

相关文章:

c++ - 递归C++函数计算: Bn(a) = Bn−1(a) × Bn−2(a) where B1(a) = B2(a) = a

C++ 自定义数组容器动态大小

c++ - 错误 : no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::__cxx11::string&)'

c++ - 整个 C++ STL 代码包含在 .h 而不是 .cpp/.c 文件中的原因是什么?

c++ - 如何复制一个非平凡的 C++ union ?

c++ - 多行标准输入 - C++

c++ - C++11 中提出的无限制 union 是什么?

c++ - constexpr 函数不需要返回常量表达式吗?

c++ - 优先队列错误

c++ - vector 的成对迭代