'std :: ios_base :: ios_base(const std :: ios_base&)'是私有'错误,同时重载operator << for std :: ostram

Kac*_*iej 6 c++ iostream ostream

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

sturct person
{
    string surname;
    person(string n) : surname(n) {};
}
Run Code Online (Sandbox Code Playgroud)

我需要重载operator<<std::ostreamperson.我写了这个函数:

std::ostream operator<<(std::ostream & s, person & os)
{
    s << os.surname;
    return s;
}
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

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

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

/usr/include/c++/4.6/ostream|57|note:这里首先要求合成方法'std :: basic_ios :: basic_ios(const std :: basic_ios&)'

jua*_*nza 18

std::ostream不是可复制构造的,当你按值返回时,你就是复制构造.虽然返回值优化意味着实际上可能没有进行复制,但编译器仍然要求可以进行复制.

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

std::ostream& operator<<(std::ostream& o, const SomeType& t);
Run Code Online (Sandbox Code Playgroud)