'std :: ios_base :: ios_base(const std :: ios_base&)'重载运算符<<<<<<<<<<对于std :: ostram

时间:2012-08-23 10:23:23

标签: c++ iostream ostream

我有一个看起来像这样的结构:

sturct person
{
    string surname;
    person(string n) : surname(n) {};
}

我需要为operator<<std::ostream重载person。我写了这个函数:

std::ostream operator<<(std::ostream & s, person & os)
{
    s << os.surname;
    return s;
}

但是我收到了这个错误:

  

/ usr / include / c ++ / 4.6 / bits / ios_base.h | 788 |错误:'std :: ios_base :: ios_base(const std :: ios_base&amp;)'是私有的|

     

/ usr / include / c ++ / 4.6 / bits / basic_ios.h | 64 |错误:在此上下文中

     

/ usr / include / c ++ / 4.6 / ostream | 57 |注意:首先需要合成方法'std :: basic_ios :: basic_ios(const std :: basic_ios&amp;)'|

3 个答案:

答案 0 :(得分:18)

std::ostream不是可复制构造的,当你按值返回时,你就是复制构造。虽然return value optimization表示实际上可能没有制作副本,但编译器仍然要求可以进行复制。

此运算符的规范返回值是非const引用:

std::ostream& operator<<(std::ostream& o, const SomeType& t);

答案 1 :(得分:3)

以参考方式返回:

std::ostream& operator<<(...)
          //^

否则,正在尝试复制s,并且ostream是不可复制的(错误消息表明尝试访​​问private复制构造函数)。

答案 2 :(得分:2)

您忘记了返回类型中的引用:

std::ostream &operator<<(std::ostream & s, person & os)
{
    return s << os.surname;
}
相关问题