子类STL向量到基类向量的转换

Conversion from STL vector of subclass to vector of base class(子类STL向量到基类向量的转换)

本文介绍了子类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向量到基类向量的转换

基础教程推荐