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

 

multisetbasket;

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.

你可能感兴趣的:(1.,C++,Primer,学习笔记)