gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:16:13 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com