如何在C ++中克隆动态类型未知的对象?

问题描述 投票:0回答:1

我想构建一个派生类对象的数组。我有这个基类:

class CandyBox {
protected:
    string flavor;
    string origin;
public:
    inline CandyBox();
    inline CandyBox(string s1, string s2);
    virtual float getVolume() = 0;
    virtual void toString();
    CandyBox& operator=(const CandyBox& obj);
    virtual ~CandyBox() {}
};

还有两个派生类,分别名为class Lindt和class ChocAmor,并带有构造函数和方法。我正在尝试建立一个像这样的草稿列表:

CandyBox** vec = new CandyBox*[n];

for (int i = 0; i < n; i++) {
    cin >> type;
    if (strcmp(type, "ChocAmor") == 0) {
        vec[i] = new ChocAmor(1, "s", "ro");
    }
    else vec[i] = new Lindt(1, 2, 3, "f", "it");
}

我的问题是:如果我想创建另一个名为CandyBag的类,该类包含这样的属性CandyBox** vec = new CandyBox*[n];,并且需要此方法,该怎么办:

CandyBag& operator=(const CandyBag& candy) {
    ChocAmor::operator=(candy);
    Lindt::operator=(candy);
    dim_max = candy.dim_max;
    current_dim = candy.current_dim;
    vec = new CandyBox*[candy.dim_max];

    for (int i = 0; i <= current_dim; i++) {
        vec[i] = new ; //HERE I'M STUCK
        // because I can't just simply write vec[i] = candy.vec[i], right?
        // I need to allocate memory for that vec[i] first
    }
    return *this;
}

如果我不知道类型(如果是vec[i]对象或ChocAmor中的Lindt类型,则不确定如何为candy.vec[i]分配内存)。我应该在存储该数组类型的位置上获得一个辅助数组吗?

c++ class oop memory-management clone
1个回答
1
投票

所有指向类类型的指针都具有相同的大小和表示形式。这对于完全不透明的指针至关重要。

如果要启用克隆指向的对象,请将虚拟.clone()添加到接口,和/或编写自己的复制智能指针。尽管在其他情况下可能是正确的解决方案,但是拖延指向克隆函数的指针或维护从typeid到克隆函数的映射将更加麻烦。

否则,我有个建议:

使用智能指针,最好是std::unique_ptr,以及标准容器,最好是std::vector,以避免手动的内存管理,并获得使用标准类型的所有相关好处。

© www.soinside.com 2019 - 2024. All rights reserved.