获得向量< Derived *>转换成期望向量< Base *>的函数。 [英] Getting a vector<Derived*> into a function that expects a vector<Base*>
问题描述
考虑这些类。
class Base
{
...
};
class Derived : public Base
{
...
};
此功能
void BaseFoo( std::vector<Base*>vec )
{
...
}
最后我的矢量
std::vector<Derived*>derived;
我想通过派生
code> BaseFoo ,但是编译器不让我。我如何解决这个问题,而不是将整个向量复制到 std :: vector< Base *>
?
I want to pass derived
to function BaseFoo
, but the compiler doesn't let me. How do I solve this, without copying the whole vector to a std::vector<Base*>
?
推荐答案
向量< Base *>
和向量< Derived *>
是不相关的类型,所以你不能这样做。有关说明,请参阅C ++常见问题这里。
vector<Base*>
and vector<Derived*>
are unrelated types, so you can't do this. This is explained in the C++ FAQ here.
您可以将变量从向量< Derived *>
更改为向量< ; Base *>
并插入派生的
对象。
You could change your variable from a vector<Derived*>
to a vector<Base*>
and insert Derived
objects into it.
应该通过const引用而不是值传递向量:
Also, you should pass the vector by const-reference, not by value:
void BaseFoo( const std::vector<Base*>& vec )
{
...
}
最后,为了避免内存泄漏,并使代码异常安全,请考虑使用一个用于处理堆分配对象的容器,例如:
Finally, to avoid memory leaks, and make your code exception-safe, consider using a container designed to handle heap-allocated objects, e.g:
#include <boost/ptr_container/ptr_vector.hpp>
boost::ptr_vector<Base> vec;
或者,更改向量以保存智能指针,而不是使用原始指针:
Alternatively, change the vector to hold a smart pointer instead of using raw pointers:
#include <memory>
std::vector< std::shared_ptr<Base*> > vec;
或
#include <boost/shared_ptr.hpp>
std::vector< boost::shared_ptr<Base*> > vec;
在每种情况下,您都需要修改 BaseFoo
函数。
In each case, you would need to modify your BaseFoo
function accordingly.
这篇关于获得向量< Derived *>转换成期望向量< Base *>的函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!