C++ 容器与继承

来源:互联网 发布:js function中onclick 编辑:程序博客网 时间:2024/05/21 06:17

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
原创粉丝点击