gpt4 book ai didi

C++ 复制一个流对象

转载 作者:可可西里 更新时间:2023-11-01 16:38:25 25 4
gpt4 key购买 nike

我一直在尝试使用 C++,但遇到了一个我不知道如何解决的问题。

基本上,我发现您无法复制流(请参阅 Why copying stringstream is not allowed? ),这也适用于“包装”它们的对象。例如:

  • 我创建了一个类,其中包含一个类型为 stringstream 的数据成员。
  • 我创建了这个类的一个对象。
  • 我尝试复制对象,例如“TestObj t1; TestObj t2; t1 = t2;”

这会导致错误 C2249:

'std::basic_ios<_Elem,_Traits>::operator =' : no accessible path to private member declared in virtual base 'std::basic_ios<_Elem,_Traits>'

所以我的问题是:如何(最好轻松)复制具有 *stream 类型数据成员的对象?

完整示例代码:

#include <iostream>
#include <string>
#include <sstream>

class TestStream
{
public:
std::stringstream str;
};

int main()
{
TestStream test;
TestStream test2;
test = test2;

system("pause");
return 0;
}

提前致谢。

更新

感谢以下答案,我已经设法解决了这个问题。我所做的是声明一次流对象,然后使用包装器对象(例如,TestStream)中的指针简单地引用它们。所有其他具有私有(private)复制构造函数的对象也是如此。

最佳答案

不允许复制流的原因是 it doesn't make sense to copy a stream .如果您解释了您正在尝试做什么,那么肯定有一种方法可以做到。如果您想要可以复制的数据 block ,请使用字符串。但是流更像是一个连接而不是一个字符串。

关于C++ 复制一个流对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7903903/

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