Conversion from STL vector of subclass to vector of base class(子类STL向量到基类向量的转换)
问题描述
我想知道是否可以将派生类值的向量转换为基类值的向量.具体来说,我希望能够将基类对象的向量传递给其形式参数采用基类向量的函数.似乎无法直接使用,因为以下代码示例会产生错误(使用 g++):
#include <vector>A类{};B类:公共A {};无效函数(std::vectorobjs){}int main(int argc, char **argv) {标准::向量<B>objs_b;objs_b.push_back(B());函数(objs_b);}
<块引用>
test.cc:16: 错误:从 'std::vector >' 转换为非标量类型 'std::vector>'请求
我希望能够调用函数,而不必定义具有 A 类型元素的新向量、插入我的 B 类型元素或更改为指针向量.
不,不是.vector
不是从 vector
派生的,而不管 B
是从 A
.您将不得不以某种方式更改您的功能.
一种更惯用的 C++ 方法可能是对其进行模板化并使用一对迭代器 - 这就是各种标准库函数(<algorithm>
等)以这种方式工作的原因,因为它将算法的实现与它所操作的事物分开.
I am wondering if it is possible to convert a vector of derived class values to a vector of base class values. Specifically I want to be able to pass a vector of base class objects to a function whose formal parameters takes a vector of base class. It does not appear to be possible directly as the following code example produces an error (using g++):
#include <vector>
class A {
};
class B : public A {
};
void function(std::vector<A> objs) {
}
int main(int argc, char **argv) {
std::vector<B> objs_b;
objs_b.push_back(B());
function(objs_b);
}
test.cc:16: error: conversion from ‘std::vector<B, std::allocator<B> >’ to non-scalar type ‘std::vector<A, std::allocator<A> >’ requested
I would like to be able to be able to call function without having to define a new vector with elements of type A, inserting my elements of type B or changing to a vector of pointers.
No, it is not. vector<B>
is not derived from vector<A>
, regardless of the fact that B
is derived from A
. You will have to change your function somehow.
A more idiomatically C++ approach might be to template it and have it take a pair of iterators - this is why the various standard library functions (<algorithm>
etc) work that way, because it separates the implementation of the algorithm from the kind of thing it's operating on.
这篇关于子类STL向量到基类向量的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:子类STL向量到基类向量的转换
基础教程推荐
- 使用scanf()读取字符串 1970-01-01
- 初始化变量和赋值运算符 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- C++ #define 1970-01-01
- C++按值调用 1970-01-01
- C++定义类对象 1970-01-01
- C语言访问数组元素 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23