如何调用存储在向量中的对象的方法?以下代码失败......
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:错误:请求 成员'printOutput'在'* 它.__ gnu_cxx :: __ normal_iterator&lt; _Iterator,_Container&gt; :: operator-&gt;与_Iterator = ClassA **,_Container = std :: vector&gt;',其中 是非类型'ClassA *'
问题似乎是it->printOutput();
,但目前我不知道如何正确调用该方法,有人知道吗?
关于mikey
答案 0 :(得分:13)
向量中的东西是指针。你需要:
(*it)->printOutput();
取消引用迭代器以从向量中获取指针,然后使用 - &gt;在调用函数的指针上。如果向量包含对象而不是指针,那么您在问题中显示的语法将起作用,在这种情况下,迭代器就像指向其中一个对象的指针一样。
答案 1 :(得分:0)
有一个Boost.PointerContainer库,可以为您提供极大的帮助。
首先:它负责内存管理,所以你不会忘记内存所指向的释放
第二:它提供了一个“解除引用”的接口,这样你就可以使用迭代器而不需要修补(*it)->
。
#include <boost/ptr_container/ptr_vector.hpp>
int main(int argc, char* argv[])
{
boost::ptr_vector<ClassA> vec;
vec.push_back(new DerivedA());
for (boost::ptr_vector<ClassA>::const_iterator it = vec.begin(), end = vec.end();
it != end; ++it)
it->printOutput();
}
从依赖注入的角度来看,您可能愿意让printOutput
获取std::ostream&
参数,以便您可以将其指向您想要的任何流(它可以完全默认为{{1 }})