【发布时间】:2021-10-28 22:52:21
【问题描述】:
我有以下课程:
class Character
{
/unimportant code
}
class Fighter : public Character
{
/unimportant code
}
class Healer: public Character
{
/unimportant code
}
class Game
{
public:
void move(const GridPoint & src_coordinates, const GridPoint & dst_coordinates);
//there are more things here ,but they're not important for the sake of this question.
private:
int height;
int width;
std::vector<std::shared_ptr<Character>> gameboard;
};
void move(const GridPoint & src_coordinates, const GridPoint & dst_coordinates)
{
for (std::vector<std::shared_ptr<Character>>::iterator i = gameboard.begin(); i !=
gameboard.end() ; i++ )
{
if ( (*gameboard[i]).coordinates == src_coordinates)
{
//do I need to implement my own [] operator?
}
}
}
我正在尝试遍历我的游戏板并将角色从 src_coordinates 移动到 dst_coordinates。 Character 也是一个被更多人继承的类:
当我尝试访问 gameboard[i] 的元素时出现以下错误:
no match for 'operator[] (operand types are 'std::vector<std::shared_ptr<Character> >' and 'std::vector<std::shared_ptr<Character> >::iterator' {aka '__gnu_cxx::__normal_iterator<std::shared_ptr<Character>*, std::vector<std::shared_ptr<Character> > >'}
这是否意味着我必须实现自己的 operator[] 和 operator* 因为 Character 是我自己的一个类?我该如何解决我的问题?
【问题讨论】:
-
您将
operator[]与索引一起使用,当您拥有迭代器时,您只需像指针一样取消引用它。所以在你的情况下,它会是 (*i)->coordinates -
因此,您有一个名为
gameboard的容器和一个名为i的迭代器,用于迭代该容器。从容器中获取底层元素的方式不是*gameboard[i]。它是……等等……*i。就像你的容器是一个普通数组,而你的迭代器是一个指针一样。 -
一个向量可以像使用
[]操作符索引的数组一样被访问。或者使用迭代器。但是迭代器不是索引。似乎您跳过了教科书或教程或课程的某些部分。此外,我建议您了解the range-basedforloop,您既不需要索引也不需要迭代器。如for (auto const& character_pointer : gameboard) -
向量已经实现了
operator[]。如果没有,您将无法实现(因为您无权访问内部)。另外,无论如何您都不需要它。为Character实现operator[]毫无意义,因为Character不是容器。 -
for (auto &gb: gameboard)会更惯用。
标签: c++ c++11 vector shared-ptr