【问题标题】:<list> retreving items problem with iterator<list> 使用迭代器检索项目问题
【发布时间】:2010-12-16 18:04:55
【问题描述】:

我有一个指令类型的列表*。教学是我做的一门课。这个类有一个叫做execute()的函数。

我创建了一个指令列表*

list<Instruction*> instList;

我创建了一个指令*

Instruction* instPtr;
instPtr = new Instruction("test",10);

如果我打电话

instPtr.execute();

该函数将正确执行,但是如果我将 instPtr 存储在 instList 中,我将无法再从列表中调用 execute() 函数。

//add to list
instList.push_back(instPtr);

//create iterator for list
list<Instruction*>::iterator p = instList.begin();
//now p should be the first element in the list
//if I try to call execute() function it will not work
p -> execute();

我收到以下错误:

error: request for member ‘execute’ in ‘* p.std::_List_iterator<_Tp>::operator-> [with _Tp = Instruction*]()’, which is of non-class type ‘Instruction*’

【问题讨论】:

  • John Kugelman 很好地解释了问题所在,但请记住,将指针存储在 STL 容器中是等待发生的资源泄漏,除非您有单独的代码来清理指令对象你创造了。您存储指向它们的指针而不是对象本身的任何具体原因?
  • 如果intrPtr 真的是一个指针,那么我不相信instPtr.execute() 会编译,更不用说正确执行函数了。你能检查你发布的代码吗?
  • @Timo:在处理继承时,存储指针是可行的方法,尽管我同意使用 Boost 指针容器可能会更好。

标签: c++ function class g++ compiler-errors


【解决方案1】:

pInstruction * 指针的迭代器。你可以把它想象成Instruction ** 类型。您需要像这样双重取消引用p

(*p)->execute();

*p 将评估为 Instruction *,并在其上进一步应用 -&gt; 运算符将取消引用指针。

【讨论】:

    【解决方案2】:

    试试(*p)-&gt;execute();

    【讨论】:

    • 遗憾的是(好吧,实际上这可能是件好事)你不能为此使用p-&gt;-&gt;execute();
    【解决方案3】:

    你需要 (*p)->execute();而不是 p->execute();

    您需要取消引用列表迭代器以获取与您的迭代器引用的列表中的节点关联的值。

    【讨论】:

      【解决方案4】:

      最好的解决方案是将 boost::shared_ptr 保留在您的列表中。请记住所有使用复制原则的 STL 容器。

      使用此代码

      列表> instList;

      然后像往常一样调用你的执行函数

      instList[i]->execute();

      如您所见,当您将指针保存在列表中时,您调用了执行。这是最好的解决方案

      【讨论】:

      • 问题不在于资源管理。您的代码之所以有效,是因为您使用了 std::list::operator[]
      • 我没说你不能用。 OP的问题与指针类型无关。它只取消引用迭代器一次而不是两次。您的解决方案两次取消引用迭代器:一次通过调用 operator[] 和另一个通过使用 ->。即使您使用相同的内置指针,它也会起作用(尽管没有按照 OP 的要求进行操作:使用 begin())
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      相关资源
      最近更新 更多