简体   繁体   English

在派生类中复制类似于构造函数的基类实例的副本

[英]Copy constructor-like copying of base class instance in the derived class

I have an unusual problem in a large system where for various reasons I might have to use a construct like this: 在大型系统中,由于各种原因,我可能不得不使用这样的构造,这是一个不寻常的问题:

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

I realize there are design flaws here, such as the chaotic transfers of pointer ownership, but is it considered really bad form to initialize a derived class object with a base class version if the data you need to copy is predominantly contained in the base class, but you need specific functionality that is only supported in the derived class? 我意识到这里存在设计缺陷,例如指针所有权的混乱转移,但是如果您需要复制的数据主要包含在基类中,那么用基类版本初始化派生类对象是否被认为是一种非常糟糕的形式,但是您需要仅在派生类中受支持的特定功能吗? Thanks a lot. 非常感谢。

With this design you get "sideways-conversion" in your class hierarchy, eg 通过这种设计,您可以在类层次结构中获得“横向转换”,例如

void foo(ItemExtension const&)

class OtherItemExtension: public Item { /* ... */ };
OtherItemExtenstion bar;

foo(bar);

Here the call to foo succeeds by creating a temporary ItemExtension from bar and passing that to foo . 在这里,通过从bar创建一个临时ItemExtension并将其传递给foo成功调用了foo Most likely that is not what you want. 这很可能不是您想要的。

Note that even if you make the constructor explicit, the following will still succeed: 请注意,即使使构造函数明确,以下操作仍将成功:

ItemExtension baz(bar);

You most likely don't want that, making it a bad idea to have that constructor. 您很可能不希望这样做,因此拥有该构造函数是一个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM