c++ 将 vector<Parent*> 的元素传递到需要 chidren 的对象的方法中

c++ passing element of vector<Parent*> into object's method requiring chidren

本文关键字:chidren 对象 方法 元素 Parent lt vector gt c++      更新时间:2023-10-16

在C 中,我有Parent类。Child1Child2等从中继承。类Child1Child2等分享父母的一些方法并具有自己的方法。

我声明vector能够添加任何Parent的孩子。

vector<Parent*> v = {new Child1(), new Child2(),...};

根据孩子的不同,我想为BClass::someMethod(Child1* child)BClass::someMethod(Child2* child)的方法定义不同的行为...类似访问者模式之类的东西。问题在于,我必须将v矢量的元素传递到BClass::someMethod(...)中,并且编译器说,例如,当传递v[0]时,方法BClass::someMethod(Child1* c1)

Argument of type Parent* is incompatible with parameter of type Child1* 

您能告诉我如何克服这个问题吗?

oop解决方案是将虚拟成员函数添加到Parent,在儿童的覆盖成员函数中实现不同的行为,然后将BClass::someMethod的参数更改为Parent指针(或参考),并在其中调用虚拟函数 - 或完全删除BClass::someMethod,并直接使用虚拟函数,以防BClass::someMethod不再具有其他功能。


P.S。将动态分配存储在裸指针中不是一个好的设计。建议使用智能指针。