使用初始化列表初始化类中的std :: ofstream

时间:2013-08-20 00:57:19

标签: c++ ofstream initializer-list

我想使用初始化列表在构造函数中初始化私有std::ofstream(例如,在main中打开的文件)。我有以下代码:

class MyClass{
    std::ofstream ofs;
public:
    MyClass(const std::ofstream &ofs): ofs(ofs) { }
};

我得到以下编译错误:

error C2248: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream' : cannot access private member declared in class 'std::basic_ofstream<_Elem,_Traits>'
      with
      [
          _Elem=char,
          _Traits=std::char_traits<char>
      ]
      c:\program files (x86)\microsoft visual studio 11.0\vc\include\fstream(1034) : see declaration of 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream'
      with
      [
          _Elem=char,
          _Traits=std::char_traits<char>
      ]

这里发生了什么?

1 个答案:

答案 0 :(得分:3)

查看cppreference

basic_ofstream( const basic_ofstream& rhs) = delete;    (5)     (since C++11)

无法复制构造basic_ofstream

您可能正在使用pre-c ++ 11编译器,它在库中标记为private