传递派生类型的std

传递派生类型的std

本文介绍了传递派生类型的std :: vector,其中需要基本类型的std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类:

class Member
{
    ....
}

以及类似的派生类:

class Mine_sweeper : private Member
{
    ....
}

然后我有一个容器:

class Population
{
public:
    std::vector<Member>& m_members;
    Population(std::vector<Member>& members);
}

当我将人口"的构造函数与成员"向量一起使用时,它会编译确定.但是,如果我尝试将Population的m_members与Mine_sweepers的向量链接,则编译器会引发错误.

When I use Population's constructor with a vector of Members it compiles OK. But if I try to link Population's m_members with a vector of Mine_sweepers, complier throws an error.

std::vector<Member> members;
Population pop(members); // this compiles OK

std::vector<Mine_sweeper> sweepers;
Population pop(sweepers); // but here I get an error
main.cpp(23): error C2664: 'Population::Population(std::vector &)' : cannot convert parameter 1 from 'std::vector' to 'std::vector &'

推荐答案

Mine_sweeper的向量不是Member的种类",即使Mine_sweeper是Member的种类"也是如此.您不能使用vector<Derived>代替vector<Base>.

Vector of Mine_sweepers is not a "kind of" vector of Members, even when Mine_sweeper is a "kind of" Member. You can not use vector<Derived> in place of vector<Base>.

使用vector<unique_ptr<Member>>代替vector<Member> AND vector<Mine_sweeper>.这样一来,您就可以拥有不同种类的成员种群(即,同时具有Mine_sweepers和其他Member子类型).

Use vector<unique_ptr<Member>> instead of vector<Member> AND vector<Mine_sweeper>. This enables you to have heterogeneous Population of Members (i.e. Mine_sweepers and other Member sub-types, at the same time).

或者,将人口"类转换为类模板:

Alternatively, convert the Population class to a class template:

class Population<T>
{
public:
    std::vector<T>& m_members;
    Population(std::vector<T>& members);
}

这样,一个人口"实例只能包含一种类型的成员.

This way, one Population instance may only contain one type of Members.

这篇关于传递派生类型的std :: vector,其中需要基本类型的std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:08