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

use*_*514 1 c++ compiler-errors g++ class function

我有一个类型说明*的列表.指导是我所做的课程.该类有一个名为execute()的函数.

我创建一个指令列表*

list<Instruction*> instList;
Run Code Online (Sandbox Code Playgroud)

我创建了一个指令*

Instruction* instPtr;
instPtr = new Instruction("test",10);
Run Code Online (Sandbox Code Playgroud)

如果我打电话

instPtr.execute();
Run Code Online (Sandbox Code Playgroud)

函数将正确执行,但是如果我将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();
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

Joh*_*ica 9

pInstruction *指针的迭代器.您可以将其视为类型Instruction **.你需要加倍解除引用p:

(*p)->execute();
Run Code Online (Sandbox Code Playgroud)

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