【发布时间】: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