2010-05-14 154 views
1

如何调用存储在向量中的对象的方法?下面的代码失败......如何通过矢量调用方法?

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();但此刻,我不知道如何正确地调用该方法,有人知道吗?

关于mikey

回答

13

向量中的东西是指针。您需要:

(*it)->printOutput(); 

其中,取消引用迭代器以获取指向矢量的指针,然后使用 - >指针来调用该函数。如果向量包含对象而不是指针,那么在问题中显示的语法将起作用,在这种情况下,迭代器就像是指向其中一个对象的指针。

+0

作品,谢谢! – 2010-05-14 10:43:38

+0

循环的数字本来就是这里比较容易的解决方案。在绝大多数情况下迭代器不需要存在实际的迭代 - 仅用于算法。 – Puppy 2010-05-14 12:51:21

+0

@DeadMG有趣 - 你如何迭代列表或地图(例如),而不使用迭代器? – 2010-05-14 12:53:46

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&参数,这样就可以直接到任何你想要的流(它可以完美地默认为std::cout

+0

请在这里没有“依赖注入” - 这是C++!我们称之为“将值传递给函数” – 2010-05-14 12:48:18

+0

我不是很了解你的评论Neil,不是依赖注入来传递引用一个对象而不是静态地访问这个对象?我不明白为什么这个术语不能应用到C++中,或者你厌恶流行语;)? – 2010-05-14 16:00:38