[英]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.