[英]Copy constructor-like copying of base class instance in the derived class
在大型系統中,由於各種原因,我可能不得不使用這樣的構造,這是一個不尋常的問題:
class Item
{
int mID;
int mID2;
...
int mIDn;
public:
Item();
Item(const Item& Other);
Item& operator=(const Item &Other);
};
class ItemExtension : public Item
{
// some data
public:
ItemExtension(const Item &Other) : Item(Other) {}
ItemExtension(const ItemExtension &Other);
ItemExtension& operator=(const ItemExtension& Other);
};
// client code
Item *Myitem = ItemList.ReleaseItem(index); // ownership transferred and an Item is removed from a list
std::auto_ptr<ItemExtension> ItemExt(new ItemExtension(*MyItem));
ItemExtList.push_back(ItemExt.release()); // store in std::vector and take ownership
我意識到這里存在設計缺陷,例如指針所有權的混亂轉移,但是如果您需要復制的數據主要包含在基類中,那么用基類版本初始化派生類對象是否被認為是一種非常糟糕的形式,但是您需要僅在派生類中受支持的特定功能嗎? 非常感謝。
通過這種設計,您可以在類層次結構中獲得“橫向轉換”,例如
void foo(ItemExtension const&)
class OtherItemExtension: public Item { /* ... */ };
OtherItemExtenstion bar;
foo(bar);
在這里,通過從bar
創建一個臨時ItemExtension
並將其傳遞給foo
成功調用了foo
。 這很可能不是您想要的。
請注意,即使使構造函數明確,以下操作仍將成功:
ItemExtension baz(bar);
您很可能不希望這樣做,因此擁有該構造函數是一個壞主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.