自动将指向派生类的指针列表转换为指向基类的指针列表 [英] automatically convert list of pointers to derived class to list of pointers to base class

查看:102
本文介绍了自动将指向派生类的指针列表转换为指向基类的指针列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个基类和派生类,以及一个使用指向基类指针的stl向量的函数:

Lets say that I have a base and derived class, and a function that takes an stl vector of pointers to the base class:

class A { public: int x; };

class B : public A { };

void foo(const vector<A*> &va) {
    for (vector<A*>::const_iterator it = va.begin(); it < va.end(); it++)
        cout << (*it)->x << endl;
}

是否可以将指针列表传递给派生类?即:

is there any way to pass a list of pointers to the derived class? ie:

vector<B*> vb;
// ... add pointers to vb ...
foo(vb);

以上内容将导致以下编译器错误:

The above will cause the following compiler error:

error: could not convert ‘vb’ from ‘std::vector<B*>’ to ‘std::vector<A*>’

即使B *可转换为A *。

Even though B* is convertible to A*.

最后,如果有普通指针的解决方案,它也可以与Boost共享指针一起使用吗?

Finally, if there is a solution for plain pointers, will it work with boost shared pointers as well?

推荐答案

std :: vector< B *>和std :: vector< A *> 在技术上不相关。 C ++不允许这样。

std::vector<B*> and std::vector<A*> are technically unrelated. C++ does not allow what you want as such.

一种解决方法……为什么没有 std :: vector< Base *> 并在其中插入 Derived 对象?这就是多态的意义,动态调度等。

A way around...Why not have a std::vector<Base*> and insert into it Derived objects? That is the point of polymorphism, dynamic dispatch et al.

这篇关于自动将指向派生类的指针列表转换为指向基类的指针列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆