简体   繁体   中英

C++:: Call class method using vector iterator?

I have a class called Room, the Room class has setPrice and display function.

I stored room objects in a vector:

room.push_back(Room("r001", 1004, 2, "small"));
room.push_back(Room("r002", 1005, 2, "small"));
room.push_back(Room("r003", 2001, 4, "small"));
room.push_back(Room("r004", 2002, 4, "small"));

In my main function, i create a display function to display all rooms. Here is my code:

void displayRoom()
{
    vector<Room>::iterator it;
    for (it = room.begin(); it != room.end(); ++it) {
         *it.display(); // just trying my luck to see if it works
    }
}

But it does not call the Room's display method.

How do I call the Room(class)'s display method (no argument) and setPrice(1 argument) method?

Dereferencing has higher priority than member access. You could add parens ( (*it).display() ), but you should just use the shortcut that was introduced long long ago (in C) for this: it->display() .

Of course the same rule applies for pointers and everything else that can be dereferenced (other iterators, smart pointers, etc.).

尝试(*it).display()或简单地 - it->display()

Iterators are a bit like pointers. So you want either:

it->display();

or:

(*it).display();

Using Vector, you can also use classic form

for(size_t x = 0; x < room.size(); x++) {
    room[x].display(); //for objects
    //room[x]->display(); //for pointers
}

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