从 baseclassptrVec 中铸造衍生类ptrVector,最好的方法是什么?
我正在获取需要传递给派生类指针向量的基类指针向量,请建议执行相同操作的最佳方法。
一种方法是
使用基类 ptr 向量大小创建一个新的派生类向量
,循环传入向量
动态转换基指针并填充派生向量。
请建议是否有更好的方法来说服编译器该向量适用于多态类型。
I am getting base class pointer vector that needed to be passed to derived class pointer vector, please suggest best way to do the same.
One way will be
create a new derived class vector with the base class ptr vector size
loop the incoming vector
dynamic cast the base pointer and fill the derived vector.
Please suggest if there is some better way to do convince the compile that the vector is for the polymorphic types.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我对问题的理解正确,那么您会遇到以下情况
问题是,尽管
Base
和Derived
通过继承相关,但类型vector ;
和vector
完全不相关。两者之间没有转换。此外,还有一个问题是
baseVec
还可能包含指向其他派生类的指针,例如
Derived2
和foo 无法处理这些。
唯一真正的解决方案是
Derived*>
并使用源向量的dynamic_cast
ed内容填充它,If I understand the question right, you have the following situation
The problem is that, although
Base
andDerived
are related through inheritance, the typesvector<Base*>
andvector<Derived*>
are completely unrelated. There is no conversion between the two.Also, there is the additional problem that
baseVec
could also contain pointers to other derived classes, such asDerived2
, andfoo
can't handle these.The only real solutions are
vector<Derived*>
and populate that withdynamic_cast
ed content of the source vector我觉得你说的这种方式是最合法的。
如果您必须强制转换向量本身,那么像下面这样的断言函数是否可以满足您的目的?
希望这有帮助
I think what you mentioned is the most legal way.
If you have to cast the vector itself, will some assertion function like the following serve your purpose?
Hope this helps
如果您确定您的
baseclassptrVector
仅具有衍生类
指针,则可以使用以下方法绕过 C++ 类型检查:If you are sure that your
baseclassptrVector
has onlyderivedclass
pointers, you can circumvent the C++ type checking with: