本文介绍了c ++:可以向量< Base>包含Derived类型的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 标题几乎说这一切。基本上,这样做是合法的: class Base { // stuff } class Derived:public Base { // more stuff } vector< Base> foo; 派生吧; foo.push_back(bar); 根据我看到的其他帖子,以下是好的,但我不想在这种情况下使用指针,因为它很难让它线程安全。 vector< Base *> foo; Derived * bar = new Derived; foo.push_back(bar); 不, Derived 对象将 切片 :所有其他成员都将被丢弃。 而不是原始指针,使用 std :: vector< std :: unique_ptr& > 。 The title pretty much says it all. Basically, is it legal to do this:class Base { //stuff}class Derived: public Base { //more stuff}vector<Base> foo;Derived bar;foo.push_back(bar);Based on other posts I've seen, the following is okay, but I don't want to use pointers in this case because it's harder to make it thread safe.vector<Base*> foo;Derived* bar = new Derived;foo.push_back(bar); 解决方案 No, the Derived objects will be sliced: all additional members will be discarded.Instead of raw pointers, use std::vector<std::unique_ptr<Base> >. 这篇关于c ++:可以向量< Base>包含Derived类型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-15 23:50