C++ 容器与继承

15.7. Containers and Inheritance

We'dlike to use containers (or built-in arrays) to hold objects that are related byinheritance.However, thefact that objects are not polymorphic affects how we can use containers withtypes in an inheritance hierarchy.

Asan example, our bookstore application would probably have the notion of abasket that represents the books a customer is buying. We'd like to be able tostore the purchases in a multiset. To define the multiset, we must specify thetype of the objects that the container will hold.When we put an object in a container, the element iscopied.

Ifwe define the multisetto hold objects of the base type

 

multiset<Item_base>basket;

Item_base base;

Bulk_item bulk;

basket.insert(base);// ok: add copy of base to basket

basket.insert(bulk);// ok: but bulk sliced down to its base part

 

Wecannot fix this problem by defining the container to hold derived objects. Inthis case, we couldn't put objects of Item_base into the container there is no standard conversion from base to derived type. We could explicitly cast a base-type object into aderived and add the resulting object to the container. However, if we did so,disaster would strike when we tried to use such an element.In thiscase, the element would be treated as if it were a derived object, but the membersof the derived part would be uninitialized.


The only viable alternative would be to use the container to hold pointers to our objects. This strategy worksbut at the cost of pushing onto our users the problem of managing the objects and pointers. The user must ensure that the objects pointed to stay around for as long as the container. If the objects are dynamically allocated, then the user must ensure that they are properly freed when the container goes away. The next section presents a better and more common solution to this problem.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值