32 继承(三)
来源:互联网 发布:阿里云ecs无法连接ftp 编辑:程序博客网 时间:2024/06/05 10:43
多重继承
#include <iostream>using namespace std;class Furniture{public: Furniture(int weight) : weight_(weight) { cout << "Furniture ..." << endl; } ~Furniture() { cout << "~Furniture ..." << endl; } int weight_;};class Bed :virtual public Furniture{public: Bed(int weight) : Furniture(weight) { cout << "Bed ..." << endl; } ~Bed() { cout << "~Bed ..." << endl; } void Sleep() { cout << "Sleep ..." << endl; } int weight_;};class Sofa: virtual public Furniture{public: Sofa(int weight) : Furniture(weight) { cout << "Sofa ..." << endl; } ~Sofa() { cout << "~Sofa ..." << endl; } void WatchTV() { cout << "Watch TV ..." << endl; } int weight_;};class SofaBed : public Bed, public Sofa{public: SofaBed(int weight) :Bed(weight), Sofa(weight),Furniture(weight) { cout << "SofaBed ..." << endl; FoldIn(); } ~SofaBed() { cout << "~SofaBed ..." << endl; } void FoldOut() { cout << "FoldOut ..." << endl; } void FoldIn() { cout << "FoldIn..." << endl; }};//在整个基础结构中,直接或间接继承虚基类的所有派生类,都必须在构造函数的成员初始化表中给出对//虚基类的构造函数的调用。如果未列出,则表示调用该虚基类的默认构造函数int main(){ SofaBed sofaBed(10); //sofaBed.weight_ = 20;//访问不明确,使用虚继承,可以解决二义性问题 //sofaBed.weight_ = 10; sofaBed.Bed::weight_ = 10; sofaBed.Sofa::weight_ = 20; sofaBed.WatchTV(); sofaBed.FoldOut(); sofaBed.Sleep(); return 0;}
先调用虚基类构造函数Furniture
调用Bed与Sofa的构造函数要按继承顺序,此时如果Furniture不是虚类,则会先调用其构造函数。Furniture的构造函数已经被最底层派生类SofaBed构造
最后调用最底层的派生类构造函数SofaBed
0 0
- 32 继承(三)
- 31 继承(三)
- (九)继承三
- C++ 继承(三)
- 继承(三)
- JavaScript中继承(三) -- 组合继承
- javascript继承(三)混合继承
- C++继承(三)通过菱形继承看virtual继承
- JavaScript继承详解(三)
- JavaScript继承详解(三)
- JavaScript继承详解(三)
- JavaScript继承详解(三)
- js学习(三)继承
- JavaScript继承详解(三)
- JavaScript继承详解(三)
- JavaScript继承详解(三)
- JavaScript继承详解(三)
- JavaScript继承详解(三)
- 160329集合
- Android官方开发文档Training系列课程中文版:数据存储之数据库存储
- IOS学习 info.plist 文件加两行代码 多线程NSThread/GCD 异步下载网络图片
- nginx_http_proxy_module,实现反向代理及缓存功能
- 浅谈Servlet的本质
- 32 继承(三)
- 如何用消息系统避免分布式事务?
- 如何将c结构数据传给lua
- Java 多数据源切换
- JSON知识点汇总
- chrome 安装
- LeetCode 205 Isomorphic Strings
- c++第三次实验
- 用IDA分析so