博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ 容器与继承
阅读量:4088 次
发布时间:2019-05-25

本文共 1846 字,大约阅读时间需要 6 分钟。

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.

转载地址:http://qyyii.baihongyu.com/

你可能感兴趣的文章
React Native应用部署/热更新-CodePush最新集成总结(新)
查看>>
react-native-wechat
查看>>
基于云信的react-native聊天系统
查看>>
网易云音乐移动客户端Vue.js
查看>>
ES7 await/async
查看>>
ES7的Async/Await
查看>>
React Native WebView组件实现的BarCode(条形码)、(QRCode)二维码
查看>>
每个人都能做的网易云音乐[vue全家桶]
查看>>
JavaScript专题之数组去重
查看>>
Immutable.js 以及在 react+redux 项目中的实践
查看>>
Vue2.0全家桶仿腾讯课堂(移动端)
查看>>
React+Redux系列教程
查看>>
react-native 自定义倒计时按钮
查看>>
19 个 JavaScript 常用的简写技术
查看>>
ES6这些就够了
查看>>
微信小程序:支付系列专辑(开发指南+精品Demo)
查看>>
iOS应用间相互跳转
查看>>
iOS开发之支付宝集成
查看>>
iOS开发 支付之银联支付集成
查看>>
iOS开发支付集成之微信支付
查看>>