1
可以说我有两个类,Base
和Derived
具有可变告诉对象是否为Derived
类型:从基础对象复制派生对象(智能)指针
class Base {
public:
Base() : is_derived(false) {}
bool is_derived;
};
class Derived : public Base {
public:
Derived() : is_derived(true) {}
int derived_only_member;
};
我有的std::shared_ptr
的一个std::set
到Base
对象:
std::set<std::shared_ptr<Base> > bases;
// Populate this set one way or another
我有必要通过设置迭代和仅复制Derived
物体插入肛门疗法类似的一组Base
共享指针:
std::set<std::shared_ptr<Base> > copies;
for(auto &b: bases) {
if(b->is_derived) {
copies.insert(/*Somehow copy the `Derived` object and assign a `std::shared_ptr<Base>` to it */);
}
}
如果我知道Base
指针指向一个Derived
对象,我怎么能复制它,这样的副本有derived_only_member
相同的值?
有没有一种方法可以做到这一点,而没有一个拷贝构造函数的参数为每个成员变量Derived
有和Base
没有?我的真实版本Derived
有许多成员,所以这将是不切实际的。
和拷贝将有'derived_only_member'与原相同的值'Derived'对象? –
@Kai当然,它会的。 – user0042