<list>使用iterator </list>撤消项目问题

时间:2009-11-15 07:48:57

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

我有一个类型说明*的列表。指导是我所做的课程。该类有一个名为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*’

4 个答案:

答案 0 :(得分:9)

pInstruction *指针的迭代器。您可以将其视为Instruction **类型。您需要加倍解除引用p,如下所示:

(*p)->execute();

*p将评估为Instruction *,并进一步应用->运算符将取消引用指针。

答案 1 :(得分:4)

尝试(*p)->execute();

答案 2 :(得分:1)

而不是p-&gt; execute()需要(* p) - &gt; execute();

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

答案 3 :(得分:0)

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

使用此代码

列表&gt; instList;

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

instList [Ⅰ] - &GT;执行();

因为你可以看到你在列表中保留指针时调用execute。这是最好的解决方案

相关问题