C ++ Copy构造函数和stl映射

时间:2013-02-22 19:45:43

标签: c++ stl copy-constructor

我有一个具有map _abilities

的Actor类

Actor类有一个复制构造函数,在此我想将此映射中的异能复制到新的actor实例。能力也有一个复制构造函数。

所以我的计划是循环我正在复制的传入的actor实例的能力图并创建新的能力。我这样做是因为每个技能实际上都会动作并修改演员,所以当我复制一个演员时,我也需要所有能力的新实例。以下代码在for循环中尝试将传入的actor的能力分配给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);
}

我不明白为什么不让我这样做。类型匹配。

1 个答案:

答案 0 :(得分:4)

actor是一个const对象。因此actor._abilities.begin()将返回const_iterator,而不是iterator

试试这个:

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

而不是:

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

在C ++ 11中,你也可以使用auto来处理const-correctness:

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

希望有所帮助。