gpt4 book ai didi

c++ - Vector of pointer to objects,需要vector的深拷贝,但是对象是继承对象的基础

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:21 26 4
gpt4 key购买 nike

我想要一个包含指向对象指针的 vector 的深层拷贝,但对象可以是 C 或 B。我知道混淆(我解释它的方式),让我举例说明。

class A {
A(const A& copyme) { }
void UnableToInstantiateMeBecauseOf() =0;
};

class B {
B(const B& copyme) : A(copyme) {}
};

class C {
C(const C& copyme) : A(copyme) {}
};

std::vector<A*>* CreateDeepCopy(std::vector<A*>& list)
{
std::vector<A*>* outList = new std::vector<A*>();

for (std::vector<A*>::iterator it = list.begin(); it != list.end(); ++it)
{
A* current = *it;
// I want an copy of A, but it really is either an B or an C
A* copy = magic with current;
outList->push_back(copy);
}

return outList;
}

如何创建您不知道其继承类型的对象的拷贝?

最佳答案

使用克隆:

Copy object - keep polymorphism

class Super
{
public:
Super();// regular ctor
Super(const Super& _rhs); // copy constructor
virtual Super* clone() const = 0; // derived classes to implement.
}; // eo class Super


class Special : public Super
{
public:
Special() : Super() {};
Special(const Special& _rhs) : Super(_rhs){};
virtual Special* clone() const {return(new Special(*this));};
}; // eo class Special

编辑:

我在你的问题中注意到你的基类是抽象的。没关系,这个模型仍然有效,我已经修改了。

关于c++ - Vector of pointer to objects,需要vector的深拷贝,但是对象是继承对象的基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4266689/

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