我一直在试验 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:
这会导致错误 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++ 复制一个流对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!