C ++:我可以投射一个向量< derived_class>到向量< base_class>在函数调用期间? [英] C++: Can I cast a vector <derived_class> to a vector <base_class> during a function call?

查看:93
本文介绍了C ++:我可以投射一个向量< derived_class>到向量< base_class>在函数调用期间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存在的类和函数,如下所示:

  class base_class {
...
}

void Func(...,vector< base_class>& vec_b,...){
//在函数内部,矢量vec_b正被重组并重新调整大小
}

,我定义了一个派生类, p>

 类derived_class:public base_class {
...
}

现在,不改变函数 Func ,我可以传递向< derived_class> 中插入,例如:

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

,使得派生类 d 经历相同的重组和重新调整大小?
我知道我可以将派生类转换为基类在一个函数调用没有问题,但一旦用向量进行播放,似乎有困难?我找不到在线的答案,所以任何建议或帮助是非常感谢。感谢。

解决方案

否。即使A是B,向量< A> 不是向量< B> 。 >

要传递一个代替另一个,你可以传递指针的向量(或使用Boost ptr_vector)。或者,您也可以使用模板来传递任何提供正确界面的矢量。



这两个都需要改变您的功能 - 基本上没有办法避免(仍然提供你想要的功能)。


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.

解决方案

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).

这篇关于C ++:我可以投射一个向量&lt; derived_class&gt;到向量&lt; base_class&gt;在函数调用期间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆