代码之家  ›  专栏  ›  技术社区  ›  Mike Dooley

如何通过向量调用方法?

  •  1
  • Mike Dooley  · 技术社区  · 16 年前

    如何调用存储在向量中的对象的方法?以下代码失败…

        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:错误:请求 _中的成员_打印输出_* 它。u gnu_cxx::u normal_iterator<_iterator,_container>::operator->with _iterator=classa**,_container=std::vector>_,which 是非类别类型__classa*_

    问题似乎是 it->printOutput(); 但是现在我不知道如何正确地调用这个方法,有人知道吗?

    尊敬的米奇

    2 回复  |  直到 16 年前
        1
  •  13
  •   anon    16 年前

    矢量中的东西是指针。你需要:

    (*it)->printOutput();
    

    它取消对迭代器的引用以从向量中获取指针,然后在指针上使用->来调用函数。如果向量包含对象而不是指针,则问题中显示的语法将有效,在这种情况下,迭代器的作用类似于指向其中一个对象的指针。

        2
  •  0
  •   Matthieu M.    16 年前

    有一个 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 )