如何调用存储在 vector 中的对象的方法?以下代码失败...
ClassA* class_derived_a = new ClassDerivedA;
ClassA* class_another_a = new ClassAnotherDerivedA;
vector<ClassA*> test_vector;
test_vector.push_back(class_derived_a);
test_vector.push_back(class_another_a);
for (vector<ClassA*>::iterator it = test_vector.begin(); it != test_vector.end(); it++)
it->printOutput();
代码检索到以下错误:
test3.cpp:47: error: request for member ‘printOutput’ in ‘* it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> with _Iterator = ClassA**, _Container = std::vector >’, which is of non-class type ‘ClassA*’
问题似乎是it->printOutput();
但目前我不知道如何正确调用该方法,有人知道吗?
问候麦基
最佳答案
vector 中的东西是指针。你需要:
(*it)->printOutput();
它取消引用迭代器以从 vector 中获取指针,然后在指针上使用 -> 来调用函数。如果 vector 包含对象而不是指针,则您在问题中显示的语法将起作用,在这种情况下,迭代器就像指向这些对象之一的指针一样。
关于c++ - 如何通过 vector 调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2833257/