5

次の方法で C++ でコンテナを使用しようとしてmapいます: キーは でstring、値は type のオブジェクトですofstream。私のコードは次のようになります。

#include <string>
#include <iostream>
#include <map>
#include <fstream>

using namespace std;

int main()
{
  // typedef map<string, int> mapType2;
  // map<string, int> foo;

  typedef map<string, ofstream> mapType;
  map<string, ofstream> fooMap;

  ofstream foo1;
  ofstream foo2; 

  fooMap["file1"] = foo1;
  fooMap["file2"] = foo2;

  mapType::iterator iter = fooMap.begin();
  cout<< "Key = " <<iter->first;
}

ただし、上記のコードをコンパイルしようとすると、次のエラーが発生します。

C:/Dev-Cpp/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/ios_base.h:
In member function `std::basic_ios<char, std::char_traits<char> >& std::basic_ios<char, std::char_traits<char> >::operator=(const std::basic_ios<char, std::char_traits<char> >&)': 
C:/Dev-Cpp/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/ios_base.h:741:
error: `std::ios_base& std::ios_base::operator=(const std::ios_base&)' is private
hash.cpp:88: error: within this context

何がうまくいかないのですか?を使用してこれを行うことができない場合map、そのようなキーと値のペアを作成する他の方法はありますか?

注: コードをテストすると、正常にmap<string, int> foo;動作します。

4

3 に答える 3

12

ストリームはコピーされることを好みません。最も簡単な解決策は、マップ内のストリームへのポインター (またはスマート ポインター) を使用することです。

typedef map<string, ofstream*> mapType;
于 2009-11-30T12:44:05.877 に答える
1

operator=プライベートでstd::ios_baseあり、そこからofstream派生します。foo1したがって、オブジェクトとをコピーすることはできませんfoo2

于 2009-11-30T12:46:57.297 に答える
1

タイプのオブジェクトはofstreamコピーできません。これは、標準ライブラリ コンテナーに配置するための前提条件です。

于 2009-11-30T12:43:50.917 に答える