【问题标题】:Problem with ostringstream and copy constructor [duplicate]ostringstream 和复制构造函数的问题[重复]
【发布时间】:2011-08-13 10:00:28
【问题描述】:

可能的重复:
Why copying stringstream is not allowed?
how copy from one stringstream object to another in C++?

编译类 T 失败,Visual C++ 和 GCC 产生 iostreams 模板错误。代码如下:

#include <sstream>

class T
{
  static T copy;

  std::ostringstream log;

  T()            {}
  T(const T& t)  {log  = t.log;}
  ~T()           {copy = *this;}
};

T T::copy;

log 数据成员类型更改为字符串使其编译和运行正常。这是合法的行为吗?

【问题讨论】:

    标签: c++ copy-constructor ostringstream


    【解决方案1】:

    C++ 中任何流类的复制构造函数和复制赋值已完成private。这意味着,您不能复制 std::ostringstream 对象:

    std::ostringstream ss;
    
    std::ostringstream ss1(ss); //not allowed - copy-constructor is private
    ss1=ss; //not allowed - copy-assignment is private
    

    【讨论】:

    • 好的,没错,但即使复制构造函数为空,我也会遇到同样的错误:T(const T&amp; t) {}
    • @Paul:发布实际代码和错误。
    • @Nawasz:代码与我上面的问题一样,将复制构造函数替换为:T(const T&amp; t) {}T(const T&amp; t) {log &lt;&lt; t.log.str();}T(const T&amp; t) {log &lt;&lt; t.log.rdbuf();}。我总是得到: 'std::basic_ios<_elem>::operator =' : 在虚拟基础'std::basic_ios<_elem>'中声明的私有成员没有可访问的路径
    • @Paul:好的。那是因为这条线 copy = *this; 调用 operator=() generated by the compiler; the generated code has this line copy.log= (*this).log` 导致问题。这意味着,如果您注释 copy=*this; 行,那么它会编译得很好。至少该错误不会出现。
    • 谢谢。我陷入了复制构造函数与赋值运算符的陷阱。
    【解决方案2】:

    std::ostringstream 不可复制,这就是您收到错误的原因。请参阅this answer 了解更多详情,了解如何解决此问题。

    T(const T& t)  {log << t.log.rdbuf(); }
    

    【讨论】:

    • 它仍然产生相同的错误:'std::basic_ios<_elem>::operator =' : 在虚拟基础'std::basic_ios<_elem>'
    【解决方案3】:

    我认为 ostringstream 没有重载的赋值(=)运算符。

    【讨论】:

      猜你喜欢
      • 2011-05-29
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 2013-10-13
      相关资源
      最近更新 更多