ここではコンパイルできないコードです:のstd ::マップとプライベートコンストラクタ
#include <map>
using namespace std;
class A;
class B {
friend class A;
int b;
B():b(1){};
B(int b_):b(b_){};
};
class A {
map<int,B> objects;
public:
void init(){
objects[2]=B(3);
}
};
int main(){
A a;
a.init();
return 0;
}
私は、エラーメッセージに理解し何からは:
/usr/include/c++/4.8/bits/stl_map.h: In instantiation of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int; _Tp = B; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, B> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = B; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]’:
foo.cc:18:24: required from here
foo.cc:9:10: error: ‘B::B()’ is private
B():b(1){};
^
In file included from /usr/include/c++/4.8/map:61:0,
from foo.cc:1:
/usr/include/c++/4.8/bits/stl_map.h:469:59: error: within this context
__i = insert(__i, value_type(__k, mapped_type()));
^
問題は、「マップ」ではありませんB
の友人なので、コンストラクタB()
を使用しないことがあります(ちなみにobjects[2]=B(3);
にはB()
が必要です)。 ~B()
もプライベートになるまで...働く
objects.insert(pair<int,B>(2,B(3)));
:
は、私は次の回避策を見つけました。したがって、B
のコンストラクタとデストラクタがプライベートの場合、A
の内部にB
のマップを作成する方法はありますか?
その他の質問:objects[2]=B(3);
はなぜB()
を使用していますか?
_ "
概略的には、あなたにあなたのコードを考えることができますBのコンストラクタとデストラクタが非公開のときに、B内のBのマップを構築する方法はありますか?「いいえ –
」*エラーメッセージでわかったことから*「どのようなエラーメッセージが表示されますか? – user2079303
なぜdownvote? –