如何多态地使用指针的数组或向量
How to use arrays or vectors of pointers polymorphically?
我在许多不同的帖子中读到过关于这个问题的文章,数组不应该多态处理,应该使用指针数组代替,它背后的原因对我来说很清楚。
但是,我找不到它是如何完成的示例,我似乎也无法让它工作。请考虑以下代码段:
#include <vector>
class Base
{
public:
Base();
virtual ~Base();
};
class Derived : Base
{
public:
Derived();
~Derived();
};
void foo( std::vector<Base*> )
{
// do something
}
int main()
{
std::vector<Derived*> bar;
foo(bar);
return 0;
}
编译它会产生错误消息
could not convert 'bar' from 'std::vector<Derived*>' to 'std::vector<Base*>
我是否错过了什么,或者设计甚至存在根本性的缺陷?提前谢谢。
std::vector<Derived*>
和std::vector<Base*>
是不同的类型,它们之间没有转换。但看起来你需要的是
std::vector<Base*> bar;
foo(bar);
即让多态性在向量元素的级别上起作用。
但是,请注意,为了使用通常意义上的多态性,Derived
必须从Base
公开继承:
class Derived : public Base
^^^^^^
或
struct Derived : Base
要完成 juanchopanza 的回答,您可以通过以下方式使用您的std::vector<Derived*>
:
void itemfoo(Base* item)
{
// do something
}
template<typename Iter>
void foo(Iter begin, Iter end) {
// do stuff per element
while(begin != end)
itemfoo(*begin++);
}
int main()
{
std::vector<Derived*> bar;
foo(bar.begin(), bar.end());
return 0;
}
如果您需要对整个范围进行操作并按Base*
进行操作,则可以执行以下操作:
void foo(Base** begin, Base** end) {
// do stuff on range [begin, end)
}
int main()
{
std::vector<Derived*> bar;
if(bar.empty())
foo(nullptr, nullptr); // or however you handle the empty range
else
foo(&bar[0], &bar[0] + bar.size());
return 0;
}
我是否错过了什么,或者设计甚至存在根本性的缺陷?
std::vector<Derived*>
的对象不能自动转换为std::vector<Base*>
。它们是两种完全不同的类型。
我可以想到以下选项来解决此问题:
-
更改
foo
以接受std::vector<Derived*>
。void foo( std::vector<Derived*> ) { // do something }
-
将
foo
更改为函数模板。template <typename T> void foo( std::vector<T*> ) { // do something with the implicit understanding that // T is derived from Base. }
-
更改调用代码以使用
std::vector<Base*>
。
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空