2016-06-21 48 views
0

所以我有一个基类家具,它也是一个抽象类,派生类Bed,Table,Chair和Desk。我正在使用指向基类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); 
     } 
    } 

不幸的是,我看,这是危险的,所以我想问问有没有这是更好的方法吗? BTW:这是我的第一篇文章的家伙不要太吝啬:d

+0

通过打开一个类型描述符,您可以单方面击败那些已经发明,实施,推广并将它们完美的面向对象编程领域的计算机科学家的工作。请使用'虚拟Furniture * clone()'。 –

+0

您可以在所有孩子实现的基类中创建一个方法,例如: make_copy(),它创建一个副本?我会推荐使用shared_ptr的 – thorsan

回答

0

添加一个纯虚函数克隆的基类,覆盖无处不在,并更换整个条件汤

furniture.push_back(furniture[index]->clone()); 
0

由于在意见建议,做一个虚函数的基类

virtual Furniture* copy() = 0; 

这孩子实现

class Bed 
{ 
    ... 
    virtual Furniture* copy() override 
    { 
     return new Bed(*this); 
    } 
    ... 
};