[英]C++ Iterating over vector of class pointers and using base function
我试图循环指向我的 class 的指针向量,我们称之为MyClass
,并在MyClass
中为向量中的每个元素调用一个方法,我们称之为MyMethod
。 那是:
std::vector<MyClass*> ClassOne;
for(auto it: ClassOne){
ClassOne[it].MyMethod();
}
但显然这行不通。 有人可以解释一下如何解决这个问题,还有我的代码实际上在做什么(而不是我认为它应该做什么)。
谢谢!
您正在使用基于范围的 for 循环,因此您应该使用
for(auto it: ClassOne){
it -> MyMethod();
}
it
不是一个索引。 它是元素(作为指针的向量的元素)本身的副本。 它可以是元素本身,通过使用
for(auto & it: ClassOne){
it -> MyMethod();
}
反而。 但这在这里不是最优的。
请注意,不建议使用纯指针。 改用聪明的。
使用时,
for(auto it: ClassOne)
{
// ...
}
it
是MyClass*
,而不是int
。 因此,您需要将对MyMethod
的调用更改为
it->MyMethod();
for
循环必须是:
for(auto it: ClassOne)
{
it->MyMethod();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.