gpt4 book ai didi

具有抽象类指针的对象的 C++ 拷贝

转载 作者:太空狗 更新时间:2023-10-29 21:14:42 27 4
gpt4 key购买 nike

考虑 Container 类,它主要存储 Box 对象的 unique_ptr vector ,并可以对它们执行一些计算。

class Container
{
private:
std::vector<std::unique_ptr<Box> > boxes_;
public:
Container(std::vector<std::unique_ptr<Box> > &&boxes): boxes_(std::move(boxes)){}
double TotalVolume() { /* Iterate over this->boxes_ and sum */ }
};

这里,Box 是一个抽象类,它有一个纯虚方法,例如 double Box::Volume()

现在,假设我在主程序中实例化了一个容器:

std::vector<std::unique_ptr<Box> > x;
x.push_back(std::move(std::unique_ptr<Box>(new SquareBox(1.0)));
x.push_back(std::move(std::unique_ptr<Box>(new RectangularBox(1.0, 2.0, 3.0)));
Container c(x);

如何复制c?我想要一个函数来复制 boxes_ 中的底层 Box 对象,但我认为用基类很难做到这一点?

最佳答案

制作拷贝的一种方法是在基类中使用“复制”虚拟方法。此方法将创建当前对象的拷贝并返回指向它的(唯一)指针。如果类中有任何包含的指针,它们也需要创建新的拷贝(深拷贝)。

存在其他方法。例如,您可以测试 vector 中的每个对象以确定其类型(使用 dynamic_cast),但这是丑陋、低效且极易出错的。

关于具有抽象类指针的对象的 C++ 拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40315760/

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