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.
- 容器与继承
- 容器与继承
- C++ 容器与继承
- 容器与继承
- C++primer学习:面象对象程序设计(5):容器与继承
- 【足迹C++primer】55、容器和继承
- C++ 学习 (容器与继承)
- C++: 继承与派生
- 【C++】类 与继承
- 继承与派生(C++)
- C++:继承与派生
- C++:顺序容器与迭代器
- [C++]接口继承与实现继承
- [C++]接口继承与实现继承
- C++:private继承与public继承
- C++:private继承与public继承
- C++:private继承与public继承
- [c++]容器类。继承类的构造和析构
- 数据库并发控制技术
- 某公司3531板子调试笔记
- c#注册表操作
- 让 C 程序更高效的 10 个建议
- 蓝桥杯算法训练——最短路(map实现邻接表)
- C++ 容器与继承
- 未亡羊先补牢-2015年03月18日
- 弦图与区间图的学习
- 用 C 语言编写一个简单的垃圾回收器
- Java语言基础——第十回 异常与异常处理
- html基本语法
- SPOJ 694. Distinct Substrings (不相同的子串的个数--后缀数组)
- 1分钟通过WIFI抓女神个人信息
- 如何成为一个C++高级程序员