简体   繁体   English

如何为具有std :: stringstream成员的类编写复制构造函数?

[英]How do I write a copy constructor for my class which has a std::stringstream member?

If I have a class like this, how should I write the copy constructor? 如果我有这样的类,我该如何编写复制构造函数?

#include <stringstream>

class MyClass {
  std::stringstream strm;
public:
  MyClass(const MyClass& other){
    //...
  }
  std::string toString() const { return strm.str(); }
};

std::stringstream has no copy constructor itself, so I can't use an initialiser list like this: std :: stringstream本身没有复制构造函数,所以我不能使用这样的初始化列表:

MyClass(const MyClass& other): strm(other.strm) {}

你可以试试这个:

MyClass(const MyClass& other): strm(other.strm.str()) {}

If your compiler does not support C++0x, or not want to use move constructor : 如果你的编译器不支持C ++ 0x,或者不想使用move构造函数

MyClass(const MyClass& other)
: strm(other.strm.str())
{
  this->strm.seekg( other.strm.tellg() );
  this->strm.seekp( other.strm.tellp() );
  this->strm.setstate( other.strm.rdstate() );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有std :: atomic成员变量的类的复制构造函数/赋值运算符出错 - Error with copy constructor/assignment operator for a class which has std::atomic member variable 如何使用std :: vector为类编写副本构造函数 <unsigned char*> 成员变量 - How to write a copy constructor for a class with std::vector<unsigned char*> member variable 具有用户定义的类成员的类的复制构造函数 - copy constructor of a class which has an user-defined class member 如何为具有私有对象作为属性的类编写move构造函数和赋值运算符? - How do I write move constructor and assignment operator for a class which has a private object as property? 如何在构造函数初始值设定项列表中初始化std :: unique_ptr对象的类成员std :: vector? - How do I initialize a class member `std::vector` of `std::unique_ptr` object in the constructor initializer list? std::ofstream 作为 class 成员删除复制构造函数? - std::ofstream as class member deletes the copy constructor? 如何编写构造函数 function 来设置向量的大小,该向量是 C++ 中的 class 的属性? - How do I write the constructor function that sets the size of a vector which is the attribute of my class in C++? 如何为将指针存储在std :: map中的模板类编写副本构造函数? - How to write a copy constructor for a template class that stores pointers in a std::map? “std::stringstream”没有名为“toString”的成员 - 'std::stringstream' has no member named 'toString' 尝试在具有 std::any 构造函数的基类中调用复制构造函数时出现问题 - Problem trying to call copy constructor in base class which has a std::any constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM