C++ copy a stream object(C++ 复制一个流对象)
问题描述
我一直在试验 C++,但遇到了一个我不知道如何解决的问题.
I've been experimenting with C++, and I've come across a problem that I don't know how to solve.
基本上,我发现您无法复制流(请参阅为什么要复制不允许使用字符串流?),这也适用于包装"它们的对象.例如:
Basically, I've discovered that you can't copy streams (see Why copying stringstream is not allowed?), and that also applies for objects that 'wrap' them. For example:
- 我使用 stringstream 类型的数据成员创建了一个类.
- 我创建了这个类的一个对象.
- 我尝试复制对象,例如TestObj t1; TestObj t2; t1 = t2;"
这会导致错误 C2249:
This causes the error C2249:
'std::basic_ios<_Elem,_Traits>::operator =' : 虚拟基类中声明的私有成员没有可访问的路径 'std::basic_ios<_Elem,_Traits>'
'std::basic_ios<_Elem,_Traits>::operator =' : no accessible path to private member declared in virtual base 'std::basic_ios<_Elem,_Traits>'
所以我的问题是:我如何(最好轻松)复制具有 *stream 类型数据成员的对象?
So my question is: how can I (preferably easily) copy objects that have data members of type *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)中的指针简单地引用它们.所有其他具有私有复制构造函数的对象也是如此.
I've managed to solve this problem thanks the answers below. What I have done is declare the stream objects once and then simply reference them using pointers in the wrapper objects (eg, TestStream). The same goes for all other objects that have private copy constructors.
推荐答案
不允许复制流的原因是 复制流没有意义.如果你解释你想要做什么,那么肯定有办法做到.如果您想要可以复制的数据块,请使用字符串.但是流更像是一个连接而不是一个字符串.
The reason you are not allowed to copy a stream is that it doesn't make sense to copy a stream. If you explain what it is that you are trying to do, there's certainly a way to do it. If you want a chunk of data you can copy, use a string. But a stream is more like a connection than a string.
这篇关于C++ 复制一个流对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 复制一个流对象


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01