重载操作符< onstream串联问题 [英] overloaded operator << on ofstream concatenation problems

查看:212
本文介绍了重载操作符< onstream串联问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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'lvalue到
'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 = simple]'

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;

因为第一次调用运算符<< 返回 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.

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

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