【问题标题】:Copy constructor-like copying of base class instance in the derived class在派生类中复制基类实例的类似构造函数的复制
【发布时间】:2012-03-11 05:33:33
【问题描述】:

我在一个大型系统中遇到了一个不寻常的问题,由于各种原因,我可能不得不使用这样的构造:

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

我意识到这里存在设计缺陷,例如指针所有权的混乱转移,但是如果您需要复制的数据主要包含在基类,但您需要仅在派生类中支持的特定功能?非常感谢。

【问题讨论】:

  • 它不是复制构造函数。它只是另一个构造函数。不要害臊。
  • @KerrekSB 我认为他只说“复制构造函数 like”,不是吗?
  • 你应该小心这个。请记住,引用会触发多态性。因此,如果您有一个具有派生类类型但通过基类引用或指针引用的对象,那么接受它的构造函数就是接受基类引用的构造函数。这对您或呼叫者来说可能是违反直觉的。

标签: c++ inheritance copy-constructor


【解决方案1】:

通过这种设计,您可以在类层次结构中获得“横向转换”,例如

void foo(ItemExtension const&)

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

foo(bar);

在这里,通过从bar 创建一个临时的ItemExtension 并将其传递给foo,对foo 的调用成功。这很可能不是您想要的。

请注意,即使您使构造函数显式,以下仍然会成功:

ItemExtension baz(bar);

您很可能不希望这样,因此拥有该构造函数是个坏主意。

【讨论】:

    猜你喜欢
    • 2018-09-24
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2012-09-28
    • 2021-03-07
    相关资源
    最近更新 更多