C++: Can I cast a vector to a vector <base_class> during a function call?

后端 未结 5 888
星月不相逢
星月不相逢 2020-12-20 16:37

I have a existed class and function which look like this:

Class base_class{
    ...
}

void Func(...,vector &vec_b,...){
    // inside          


        
相关标签:
5条回答
  • 2020-12-20 17:00

    No.

    You can let Func take vector <base_class*> and let the point elements in the vector <base_class*> point to derived_class instances.

    0 讨论(0)
  • 2020-12-20 17:03

    Substituting a vector of a base class with a vector of a derived class won't work if the two classes have different sizes. This is because the vector stores contiguous instances of the type internally, so the vector of bases would think the second element was in a different location than it actually is. You could use vectors of pointers, however.

    0 讨论(0)
  • 2020-12-20 17:07

    No, you cannot convert between vectors of different types. However, you can achieve what you're trying to do by making Func a template. It probably won't require you to change any code in the actual function body, but it depends on what you're doing.

    template<typename T>
    void Func(..., vector<T> &vec_b, ...){
        // inside the function, the vector vec_b is being re-organized and re-sized
    }
    
    0 讨论(0)
  • 2020-12-20 17:14

    No. Even if an A is a B, a vector<A> is not a vector<B>.

    To pass one in place of the other, you can pass a vector of pointers (or use a Boost ptr_vector). Alternatively, you may be able to use a template to allow passing a vector of anything that provides the right interface.

    Either of these will require changing your function though -- there's essentially no way to avoid that (and still provide the functionality you want).

    0 讨论(0)
  • 2020-12-20 17:21

    This only works if you're using pointers.

    If you're not using pointers, then there is a chance for slicing to occur. Eg.

    class Base {
      protected:
        int foo;
    };
    
    class Child : public Base {
        int bar;
    };
    

    The class Base contains only a single int called foo, and the class Child contains two ints, foo and bar.

    Child f;
    Base sliced = (Child)f;
    

    This will slice the child, causing it to remove some of the data from the object. You will not be able to cast the parent back into the child class, not unless your using pointers.

    So, if you changed your vector<> to have pointers instead of instances of the class then you can cast back and forth between parent/child.

    Using something like:

    vector<Base*> vec;
    vec[0] = static_cast<Base*>(new Child());
    
    ...
    Func(vec);
    ...
    

    Would allow you to cast the members of your vector into their child classes.

    0 讨论(0)
提交回复
热议问题