2013-02-22 58 views
2

我有了地圖_abilitiesC++拷貝構造函數和STL地圖

的演員類有一個拷貝構造函數的演員類,並在這裏面我想的能力,在這個地圖複製到新的演員實例。能力也有一個拷貝構造函數。

所以我的計劃是循環通過我從中複製的actor actor實例的能力圖並創建新的能力。我這樣做是因爲每個能力實際上都扮演着角色並修改了角色,因此當我複製角色時,我需要所有角色的新實例。下面的代碼讓我在一個錯誤的for循環,當它試圖在分配演員的能力傳遞給ITER:

error C2679: binary '=' : no operator found which takes a right-hand operand of type  'std::_Tree_const_iterator<_Mytree>' (or there is no acceptable conversion) 
1>   with 
1>   [ 
1>    _Mytree=std::_Tree_val<std::_Tmap_traits<std::string,Ability  *,std::less<std::string>,std::allocator<std::pair<const std::string,Ability *>>,false>> 
1>   ] 
1>   c:\program files\microsoft visual studio 10.0\vc\include\xtree(429): could be 'std::_Tree_iterator<_Mytree> &std::_Tree_iterator<_Mytree>::operator =(const std::_Tree_iterator<_Mytree> &)' 
1>   with 
1>   [ 
1>    _Mytree=std::_Tree_val<std::_Tmap_traits<std::string,Ability *,std::less<std::string>,std::allocator<std::pair<const std::string,Ability *>>,false>> 
1>   ] 
1>   while trying to match the argument list '(std::_Tree_iterator<_Mytree>, std::_Tree_const_iterator<_Mytree>)' 
1>   with 
1>   [ 
1>    _Mytree=std::_Tree_val<std::_Tmap_traits<std::string,Ability *,std::less<std::string>,std::allocator<std::pair<const std::string,Ability *>>,false>> 
1>   ] 

// _abilities define as 
map<string, Ability*> _abilities; 

Actor::Actor(const Actor& actor) 
{ 
// make a copy of this actors model and stats 
_model = CopyEntity(actor._model); 
_stats = actor._stats; 

// copy the abilities and assign this as the new actor 
map<string, Ability*>::iterator iter; 
for(iter = actor._abilities.begin(); iter != actor._abilities.end(); ++iter) 
    _abilities[(*iter).first] = new Ability(*(*iter).second, this); 
} 

我不明白爲什麼它不會讓我做這件事。類型匹配。

回答

4

actor是一個const對象。所以actor._abilities.begin()將返回const_iterator,而不是iterator

試試這個:

map<string, Ability*>::const_iterator iter; 

,而不是這樣的:

map<string, Ability*>::iterator iter; 

在C++ 11,可以使用auto這需要常量,正確性也照顧:

for(auto iter = actor._abilities.begin(); /* same as before */) 
     _abilities[iter->first] = new Ability(*(iter->second), this); 
} 

希望有所幫助。

+1

已解決,謝謝! – user441521 2013-02-22 19:59:03