gpt4 book ai didi

c++ - 从基础对象(智能)指针复制派生对象

转载 作者:太空宇宙 更新时间:2023-11-04 12:58:53 25 4
gpt4 key购买 nike

假设我有两个类(class),BaseDerived有一个变量来判断对象是否属于 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::setstd::shared_ptrBase对象:

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有很多成员,所以这是不切实际的。

最佳答案

Is there a way to do this without a copy constructor that has an argument for every member variable that Derived has and Base doesn't?

复制构造函数不需要每个成员变量的参数。编译器也已经为您生成了一个。

你需要的是类型转换:

std::set<std::shared_ptr<Base> > copies;
for(auto &b: bases) {
if(b->is_derived) {
copies.insert(std::make_shared<Derived>(static_cast<Derived>(*b)));
// ^^^^^^^^^^^^^^^^^^^^^ ^
}
}

注意:

您甚至不需要 is_derived 成员来检查从 Base 派生的实例。您可以改用 dynamic_cast:

std::set<std::shared_ptr<Base> > copies;
for(auto &b: bases) {
Derived* org = dynamic_cast<Derived*>(b.get());
if(org) {
copies.insert(std::make_shared<Derived>(*org));
}
}

关于c++ - 从基础对象(智能)指针复制派生对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45174747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com