6

我有以下代码:

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):

错误:无法将“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<<(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 * “标签”)在重载解决方案后中断,但我真的不明白到底是什么正在这里进行。我想清楚地了解编译器正在尝试做什么..

4

1 回答 1

17

在线上 :

f << "label: " << s;

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

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

于 2011-01-09T18:46:45.750 回答