2

我有一个具有 map _abilities 的 Actor 类

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

所以我的计划是循环遍历我要复制的传入actor实例的能力映射并创建新能力。我这样做是因为每个能力实际上都会起作用并修改演员,所以当我复制演员时,我还需要所有能力的新实例。以下代码在尝试将传入的演员能力分配给迭代器时,在 for 循环中给了我一个错误:

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

1 回答 1

4

actor是一个常量对象。所以actor._abilities.begin()会返回const_iterator,不会iterator

试试这个:

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

而不是这个:

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

在 C++11 中,您还可以使用autowhich 来处理 const 正确性:

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

希望有帮助。

于 2013-02-22T19:49:48.107 回答