c++ 将 vector<Parent*> 的元素传递到需要 chidren 的对象的方法中
c++ passing element of vector<Parent*> into object's method requiring chidren
在C 中,我有Parent
类。Child1
,Child2
等从中继承。类Child1
,Child2
等分享父母的一些方法并具有自己的方法。
我声明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。将动态分配存储在裸指针中不是一个好的设计。建议使用智能指针。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- c++ 将 vector<Parent*> 的元素传递到需要 chidren 的对象的方法中