使用迭代器访问存储在向量中的类对象的方法。如何?
嘿,我在这里问第一个问题,非常感谢。 我使用向量来存储一系列指向 CSquare 类对象的指针,我想要一个可以传递的迭代器,以便我可以访问某个对象的函数。这是我当前尝试此操作的代码,但没有成功。 IntelliSense 告诉我“没有可用的成员”。
vector <CSquare*> pSquares;
//filled in vector
vector<CSquare*>::iterator tempIt = pSquares.begin();
tempIt->getName();
不知道还要添加什么,但如果您需要其他任何内容来帮助我,请说。
再次非常感谢。
编辑:问题解决了,我不得不取消引用两次。下面的代码有效,我想我会保留它以防其他人需要相同的帮助,无论如何感谢您的关注。
vector <CSquare*> pSquares;
//filled in vector
vector<CSquare*>::iterator tempIt = pSquares.begin();
(**tempIt).getName();
Hey first question I'm asking here many thanks in advance.
I'm using a vector to store a series of pointers to objects of a class CSquare, I want to have an iterator that I can pass around so that I can access the functions of a certain object. This is my current code to attempt this with no luck. IntteliSense telling me that there are 'No members Available'.
vector <CSquare*> pSquares;
//filled in vector
vector<CSquare*>::iterator tempIt = pSquares.begin();
tempIt->getName();
Not sure what else to add, but if you need anything else to help me out please say.
Again thanks a lot.
Edit: Problem solved, I had to dereference twice. The following code works, thought I'd just leave this up incase anyone else need the same help, thanks for looking anyway.
vector <CSquare*> pSquares;
//filled in vector
vector<CSquare*>::iterator tempIt = pSquares.begin();
(**tempIt).getName();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请记住,您需要取消引用迭代器才能获取指向的内容。因为这是一个
vector
,所以您的迭代器实际上是一个指向CSquare
的指针,因此您需要执行以下操作:Remember that you need to dereference the iterator to get the pointed-to thing. Because this is a
vector<CSquare*>
, your iterator is effectively a pointer-to-pointer-to-CSquare
, so you need to do this:您需要额外的取消引用:
原因是您在向量中存储的是指针,因此 *tempIt 是对指针的引用,您需要再次取消引用才能访问 CSquare< /代码> 对象。
You need an extra dereference:
The reason is that what you are storing inside the vector are pointers, so
*tempIt
is a reference to a pointer that you need to dereference again to access theCSquare
object.