How to call a method via a vector?

前端 未结 2 1708
日久生厌
日久生厌 2020-12-21 22:12

How do I call a method of an object which is stored within a vector? The following code fails...

    ClassA* class_derived_a = new ClassDerivedA;
    ClassA*         


        
2条回答
  •  醉梦人生
    2020-12-21 22:50

    There is a Boost.PointerContainer library which could help you tremendously here.

    First: it takes care of memory management, so you won't forget the release the memory pointed to.
    Second: it provides a "dereferenced" interface so that you can use the iterators without the ugly patching (*it)->.

    #include 
    
    int main(int argc, char* argv[])
    {
      boost::ptr_vector vec;
      vec.push_back(new DerivedA());
    
      for (boost::ptr_vector::const_iterator it = vec.begin(), end = vec.end();
           it != end; ++it)
        it->printOutput();
    }
    

    From a Dependency Injection point of view, you might be willing to have printOutput takes a std::ostream& parameter so that you can direct it to whatever stream you want (it could perfectly default to std::cout)

提交回复
热议问题