考虑Container
类,它基本上存储了unique_ptr
的矢量对象,并且可以对它们执行一些计算。具有抽象类指针的对象的C++副本
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
副本?我想要一个功能,使底层Box
对象的副本boxes_
,但我认为这很难做到这一点与基类?
无论如何,你为什么不使用std :: vector? –
Danh
谢谢:C'tor变了。至于不使用'vector','Container',实际上是一个具有虚拟'TotalVolume'方法的基类的派生类。我原来的问题不是盒子和容器,而是一些我试图扩展的复杂项目。 –
Salmonstrikes