简体   繁体   中英

Accessing a method of a class object stored in a vector using an Iterator. How?

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();

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)->getName();

You need an extra dereference:

(*tempIt)->getName();

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 the CSquare object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM