【问题标题】:problem with operator[] when trying to access a vector of shared_ptr尝试访问 shared_ptr 的向量时出现 operator[] 的问题
【发布时间】: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-based for loop,您既不需要索引也不需要迭代器。如for (auto const&amp; character_pointer : gameboard)
  • 向量已经实现了operator[]。如果没有,您将无法实现(因为您无权访问内部)。另外,无论如何您都不需要它。为Character 实现operator[] 毫无意义,因为Character 不是容器。
  • for (auto &amp;gb: gameboard) 会更惯用。

标签: c++ c++11 vector shared-ptr


【解决方案1】:

迭代器是指针的泛化。您使用* 从指针中获取指向的东西;您使用* 获取迭代器当前“指向”的容器元素。迭代器类型使用运算符重载,因此即使底层容器不是简单的数组,它也可以像指针一样工作。

std::vector<std::shared_ptr<Character>>::iterator

意味着:“当您将* 应用于它时,它会为您提供来自std::vector&lt;std::shared_ptr&lt;Character&gt;&gt;std::shared_ptr&lt;Character&gt;(以及其他有用的属性)”。 p>

每次循环,*i 是向量中的std::shared_ptr&lt;Character&gt;s 之一。因此,(*i)-&gt;coordinatesshared_ptr 指向的Character 的坐标。 (注意-&gt;,因为我们还必须取消引用shared_ptr。)

'operator[] 不匹配

发生这种情况是因为您尝试将迭代器当作索引来使用。您可以清楚地看到以下代码有什么问题:

char[] example = "hello, world\n";
char* ptr = &example[0];
example[ptr]; // wait, what?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2019-12-26
    • 2020-08-25
    • 2023-04-10
    • 2021-12-30
    • 2022-06-21
    相关资源
    最近更新 更多