重载运算符<< on ofstream concatenation problems

abi*_*gli 6 c++ operator-overloading concatenation ofstream

我有以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我试图理解为什么#1工作,而在尝试使用重载运算符连接时出现问题,因为#2失败并出现以下错误(MacOSX上的gcc 4.5.3):

错误:无法将'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:错误:初始化'std :: basic_ostream <_CharT,_Traits>&std :: operator <<的参数1(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)
{ ... }
Run Code Online (Sandbox Code Playgroud)

听起来像是与重载决策相关的东西,其中有一些插入到ofstream中的东西已经提供了重载(在这种情况下是const char*"label")在重载解析后会崩溃,但我无法真正理解究竟是什么正在这里.我想清楚地了解编译器尝试做什么.

ice*_*ime 17

在线上 :

f << "label: " << s;
Run Code Online (Sandbox Code Playgroud)

因为第一次调用operator<<返回a std::ostream &,第二次调用无法编译:操作符的左操作数不再是类型std::ofstream,并且找不到重载.

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

  • 如果使用签名`template <class Ch,class Tr> std :: basic_ostream <Ch,Tr>&operator <<(std :: basic_ostream <Ch,Tr>&),您可以进一步概括函数以使用任何字符特征. s,const simple&obj);` (2认同)