Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

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

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

Class base_class{
    ...
}

void Func(...,vector<base_class> &vec_b,...){
    // inside the function, the vector vec_b is being re-organized and re-sized
}

and I defined a derived class which looks like:

Class derived_class: public base_class{
    ...
}

Now, without changing the function Func, can I pass a vector<derived_class> into Func, ex:

void main(){
    vector <derived_class> d;
    Func(...,d,...);
}

such that the derived class d undergoes the same re-organizing and re-sizing? I know I can cast derived class to base class in a function call with no problem, but once with a vector into play, there seems to be difficulties? I can't find the answer online, so any suggestions or help is greatly appreciated. thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...