首页 > 解决方案 > 取消引用指针列表的迭代器

问题描述

我在尝试取消引用 a 的迭代器时遇到问题std::list<std::unique_ptr<MyClass>>。这是我的情况:在 headerFile.h 我有

class MyClass{
public:
   bool variable = false;
private:
};

然后在 headerFile2.h

#include "headerFile.h"
#include <memory>
#include <list>
class OtherClass{
public:
private:
   std::list<std::unique_ptr<MyClass>> MyList;
   void MyFuction();
};

最后,在 headerFile2.cpp 中,我尝试像这样使用 MyClass::variable:

#include "headerFile2.h"
void OtherClass::MyFunction(){
   for(auto it = MyList.begin(); it != MyList.end(); it++){
      *it -> variable = true;
   }
}

它不会编译,我不知道我的错误在哪里。错误信息是 'struct std::_List_iterator<std::unique_ptr<MyClass> >' has no member named 'variable'

我也试过做**it.variable = true;

我会很感激任何建议。

标签: c++iteratoroperator-precedence

解决方案


operator->优先级高于operator*,因此*it -> variable = true;被解释为*(it -> variable) = true;,whileit -> variable无效。

您可以将括号添加为

(*it) -> variable = true;

**it.variable = true;有类似的问题;你可以(**it).variable = true;


推荐阅读