从子类的STL向量到基类的向量的转换 [英] Conversion from STL vector of subclass to vector of base class
问题描述
我想知道是否可以将派生类值的向量转换为基类值的向量。具体来说,我想能够传递一个基类对象的向量到一个函数,其形式参数接受基类的向量。它似乎不可能直接作为下面的代码示例产生错误(使用g ++):
#include< vector> ;
class A {
};
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从'std :: vector< B,std :: allocator< B>'到非标量类型'std :: vector >
我想能够调用函数,而不必定义一个新的向量元素类型A,插入我的元素类型B或更改为向量
不,不是。 不是从
派生自向量< A>
派生的向量
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向量到基类的向量的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!