gpt4 book ai didi

c++ - 对一个对象使用cout,为什么需要引用调用

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:12 25 4
gpt4 key购买 nike

在下面的例子中,我想知道为什么我们使用对ostream的引用调用。我在删除 & 但没有完全收到错误消息时遇到错误。

 class MyArray{
private:
int x[10];
public:
MyArray(int n)
{
for (int i = 0; i < 10; i++)
x[i] = n;


}
friend ostream& operator<<(ostream& pa, MyArray ob);
};
ostream& operator<<(ostream& pa, MyArray ob)
{
for (int i = 0; i < 10; i++)
pa << ob.x[i];
return pa;



}
int main()
{

MyArray a(5);
cout << a;
return 0;
}

最佳答案

std::ostream 没有“可访问的”移动或复制构造函数。从 C++11 开始,复制构造函数被删除,甚至移动构造函数也被保护

当您按值返回时,(即使发生复制省略,也需要移动/复制构造函数):

ostream operator<<(ostream& pa, MyArray ob){
for (int i = 0; i < 10; i++)
pa << ob.x[i];
return pa; //Move or Copy Constructor is required.
}

................

std::ostream应该是执行高级流输出操作的对象的基类。它应该是控制 stream buffer 的对象的基类.

复制 std::cout 没有意义,因为它是一种资源,并且指定用于控制负责将字符发送到程序标准输出的流缓冲区。

关于c++ - 对一个对象使用cout,为什么需要引用调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42790991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com