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++ 复制一个流对象
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
