C ++复制一个流对象 [英] C++ copy a stream object

查看:291
本文介绍了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>运算符=':在虚拟库中声明的私有成员的可访问路径'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;
}

提前感谢。

UPDATE

我已经设法解决这个问题,感谢下面的答案。我所做的是声明一次流对象,然后使用指针在包装器对象(例如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 ++复制一个流对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆