简体   繁体   中英

C++ Iterating over vector of class pointers and using base function

I am trying to loop over a vector of pointers to my class, let's call it MyClass , and call a method within MyClass for each element in the vector, let's call it MyMethod . That is:

std::vector<MyClass*> ClassOne;
for(auto it: ClassOne){
    ClassOne[it].MyMethod();
}

But evidently this does not work. Could someone please explain how to fix this but also what my code here is actually doing (as opposed to what I thought it should be doing).

Thanks!

You are using range-based for loop, hence you should be using

for(auto it: ClassOne){
    it -> MyMethod();
}

it is not an index. It's a copy of the element (the element of the vector which is a pointer) itself. It can be the element itself by using

for(auto & it: ClassOne){
    it -> MyMethod();
}

instead. but this is not optimal here.

Please, note that it's not recommended to use plain pointers. use smart ones instead.

When you use,

for(auto it: ClassOne)
{
   // ...
}

it is a MyClass* , not an an int . Hence you need to change the call to MyMethod to

it->MyMethod();

The for loop needs to be:

for(auto it: ClassOne)
{
   it->MyMethod();
}

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