c++ - 为什么必须使用引用来返回/传递 std::ostream?

标签 c++

为什么我的代码出现错误:

ostream operator<<(ostream flux, Perso const A)
{
    A.O_Show(flux);
    return flux;
}
error: use of deleted function 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)'|

并且没有错误:

ostream& operator<<(ostream& flux, Perso& const A)
{
    A.O_Show(flux);
    return flux;
}

你能解释一下有什么区别吗?

最佳答案

至于你的代码

ostream operator<<(ostream flux, Perso const A) {
    A.O_Show(flux);
    return flux;
}

您无法复制 std::ostream作为返回值(在 标准之前,甚至这些在第一名也是 protected ),只需将代码更改为

ostream& operator<<(ostream& flux, Perso& const A) {
    // ^
    A.O_Show(flux);
    return flux;
}

关于c++ - 为什么必须使用引用来返回/传递 std::ostream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24048592/

相关文章:

c++ - 对函数的重新定义和模糊调用具有数组参数

c++ - 如何比 O(n^2) C++ 更快地打印所有不同对的计数,它们的总和等于 k?

c++ - 如何仅使用主键和静态列更新 Cassandra 表?

c++ - 使用 GCC 4.2.1 在 C++ 中将 char 输出为十六进制流

c++ - 继承,调用基类构造器

javascript - javascript 中的闭包是否与 C++ 中的类实例(具有私有(private)成员和公共(public)方法)相当?

c++ - 如何连接二维数据数组

c++ - 将 char 指针的一部分复制到另一个

c++ - 搜索算法中的时钟函数通常返回 0

c++ - 从 Object<const T> 转换为 Object<t>