重载的运算符& lt;& lt;流级联问题 [英] overloaded operator << on ofstream concatenation problems

查看:73
本文介绍了重载的运算符& lt;& lt;流级联问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

struct simple
{
    simple (int a1, int a2) : member1(a1), member2(a2) {}
    int member1;
    int member2;
};

std::ofstream &operator << (std::ofstream &f, const simple &obj)
{
    f<<obj.member1<<", "<<obj.member2;
    return f;
} 
int main(int argc, const char *argv[])
{
    std::ofstream f("streamout.txt");

    simple s(7,5);
    f << s;               //#1 This works
    f << "label: " << s;  //#2 This fails

    return 0;
}

我试图理解为什么#1可以工作,而在尝试使用重载运算符将其像#2那样进行连接时却出现了问题,但出现以下错误(在MacOSX上为gcc 4.5.3):

I'm trying to understand why #1 works, while there are problems when trying to use the overloaded operator concatenating it as in #2 which fails with the following error (gcc 4.5.3 on MacOSX):

错误:无法绑定'std :: basic_ostream'左值'std :: basic_ostream&'/GCC-FACTORY/4.5/INSTALL/lib/gcc/x86_64-apple-darwin10.5.0/4.5.3/../../../../include/c++/4.5.3/ostream:579:5:错误:初始化参数1'std :: basic_ostream< _CharT,_Traits>&std :: operator<<(std :: basic_ostream< _CharT,_Traits>&& ;, const _Tp&)[with _CharT = char,_Traits =std :: char_traits,_Tp =简单]'

error: cannot bind 'std::basic_ostream' lvalue to 'std::basic_ostream&&' /GCC-FACTORY/4.5/INSTALL/lib/gcc/x86_64-apple-darwin10.5.0/4.5.3/../../../../include/c++/4.5.3/ostream:579:5: error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char, _Traits = std::char_traits, _Tp = simple]'

如果我将运算符定义为

std::ostream &operator << (std::ostream &f, const simple &obj)
{ ... }

类似于过载解析的声音,在ofstream中插入已经提供了过载的东西(在这种情况下为const char *"label"),在过载解析后会破裂,但是我不能真正做到这一点.了解这里到底发生了什么.我想清楚地了解编译器正在尝试执行的操作.

Sounds like something related to overload resolution, where having a something inserted in the ofstream for which there's already a provided overload (the const char * "label" in this case) breaks up following overload resolution, but I can't really understand what exactly is going on here. I'd like to get a clear picture of what the compiler's trying to do..

推荐答案

在线:

f << "label: " << s;

由于第一次调用 operator<< 会返回 std :: ostream& ,因此第二次编译失败:运算符的左操作数不是再输入 std :: ofstream ,就不会找到您的重载.

Because the first call to operator<< returns a std::ostream &, the second fails to compile : the left operand to the operator is not of type std::ofstream anymore and your overload is not found.

您应该真正使用第二个签名,因为我认为没有理由将您的类型限制为输出到 std :: ofstream .

You should really use the second signature, as I see no reason for restricting your type to be outputted to std::ofstream.

这篇关于重载的运算符&amp; lt;&amp; lt;流级联问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆