假设我有一个基类和派生类,以及一个接受指向基类的指针的 STL vector 的函数:
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;
}
有什么方法可以将指针列表传递给派生类吗?即:
vector<B*> vb;
// ... add pointers to vb ...
foo(vb);
以上会导致下面的编译错误:
error: could not convert ‘vb’ from ‘std::vector<B*>’ to ‘std::vector<A*>’
即使 B* 可以转换为 A*。
最后,如果有普通指针的解决方案,它是否也适用于 boost 共享指针?
最佳答案
std::vector<B*> and std::vector<A*>
在技术上是无关的。 C++ 不允许您这样做。
解决方法...为什么不使用 std::vector<Base*>
并插入其中 Derived
对象?这就是多态性、动态调度等的意义所在。
关于c++ - 自动将指向派生类的指针列表转换为指向基类的指针列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12868347/