Getting a vectorlt;Derived*gt; into a function that expects a vectorlt;Base*gt; (获取向量lt;Derived*gt;转换为期望向量Base*的函数.)
问题描述
考虑这些类.
class Base
{
...
};
class Derived : public Base
{
...
};
这个功能
void BaseFoo( std::vector<Base*>vec )
{
...
}
最后是我的向量
std::vector<Derived*>derived;
我想将 derived 传递给 BaseFoo 函数,但编译器不允许我这样做.如何解决这个问题,而不将整个向量复制到 std::vector?
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*>?
推荐答案
vector 和 vector 是不相关的类型,所以你不能这样做.这在 C++ FAQ 这里 中有解释.
vector<Base*> and vector<Derived*> are unrelated types, so you can't do this. This is explained in the C++ FAQ here.
您需要将变量从 vector 更改为 vector 并插入 Derived 对象进入它.
You need to change your variable from a vector<Derived*> to a vector<Base*> and insert Derived objects into it.
此外,为了避免不必要地复制 vector,您应该通过常量引用而不是值来传递它:
Also, to avoid copying the vector unnecessarily, you should pass it 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*>的函数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取向量<Derived*>转换为期望向量<Base*>的函数.
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
