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