我正在使用一个STL列表来保存我的"对象"对象的指针.
我宣布:
list<Object*> objectlist;
Run Code Online (Sandbox Code Playgroud)
并插入:
this->objectlist.push_back(new Object(address,value,profit));
Run Code Online (Sandbox Code Playgroud)
并试图像地图和其他人一样迭代:
list<Object*>::iterator iter;
iter = this->objectlist.begin();
while(iter != this->objectlist.end())
{
iter->print();
}
Run Code Online (Sandbox Code Playgroud)
其中print()是类Object的公共方法;
这里有什么不对?
我无法通过迭代器访问列表中的对象?
RC.*_*RC. 32
你需要 (*iter)->print();
由于你有一个指针的迭代器,你必须首先取消引用迭代器(它得到你Object*)然后箭头取消引用它Object *并允许打印调用.
你没有增加你的迭代器!将while循环更改为for循环,如下所示:
for (list<Object*>::const_iterator iter = this->objectlist.begin(),
end = this->objectlist.end();
iter != end;
++iter)
{
(*iter)->print();
}
Run Code Online (Sandbox Code Playgroud)
(也可以像其他答案所指出的那样对指针进行iter 解引用.)