![](/img/trans.png)
[英]Is there a way to copy a vector of derived class pointers without casting it to the base class?
[英]How to implement a copy constructor of the derived class on a vector of pointers to base class which has instances of derived classes?
因此,我有一个基类家具,它也是一个抽象类,而派生类是床,桌子,椅子和桌子。 我正在使用指向基类Furniture的指针向量,并且在其中保存了派生类的实例。 我还有另一个类的收银机,它使用家具矢量进行操作。 我必须使用我制作的派生类的副本构造函数,而此代码段的想法是让我以最安全的方式克隆保存在基类的指针向量中的派生类对象可能。 这些是我的复制构造函数:
explicit Desk(const Desk& _desk) : Furniture(_desk), numberOfDrawers(_desk.numberOfDrawers) {};
explicit Table(const Table& _table) : Furniture(_table), numberOfLegs(_table.numberOfLegs) {};
explicit Chair(const Chair& _chair) : Furniture(_chair), numberOfLegs(_chair.numberOfLegs) {};
explicit Bed(const Bed& _bed) : Furniture(_bed), size(_bed.size) {};
到目前为止,我想到的方式是:
std::cout << "The object is found: " << furniture[index]->getName() << std::endl;
std::cout << "Price: " << furniture[index]->getPrice() << std::endl;
std::cout << "Code: " << furniture[index]->getCode() << std::endl;
std::cout << "Do you want to copy the purchase of " << furniture[index]->getName() << " ? (Y/N)";
char read;
std::cin >> read;
if (read == 'Y')
{
if (furniture[index]->getName() == "Bed") {
Bed* deskClone = new Bed(dynamic_cast<Bed&>(*furniture[index]));
furniture.push_back(deskClone);
}
if (furniture[index]->getName() == "Desk") {
Desk* bedClone = new Desk(dynamic_cast<Desk&>(*furniture[index]));
furniture.push_back(bedClone);
}
if (furniture[index]->getName() == "Table") {
Table* tableClone = new Table(dynamic_cast<Table&>(*furniture[index]));
furniture.push_back(tableClone);
}
if (furniture[index]->getName() == "Chair") {
Chair* chairClone = new Chair(dynamic_cast<Chair&>(*furniture[index]));
furniture.push_back(chairClone);
}
}
不幸的是,我读到这很危险,所以我想问一下是否有更好的方法来解决这个问题? 顺便说一句:这是我的第一个帖子,伙计们不要太刻薄:D
向基类添加一个纯虚拟克隆函数,覆盖所有地方,并用替换整个有条件的汤
furniture.push_back(furniture[index]->clone());
如注释中所建议,在基类中创建一个虚函数
virtual Furniture* copy() = 0;
孩子们实施的
class Bed
{
...
virtual Furniture* copy() override
{
return new Bed(*this);
}
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.