设为首页 加入收藏

TOP

C++中组合和继承的概念及意义(三)
2019-05-23 22:14:19 】 浏览:131
Tags:组合 继承 念及 意义

    1,继承是 C++ 中代码复用的重要手段。通过继承,可以获得父类的所有功能,并且可以在子类中重写已有功能,或者添加新功能;

 

16,继承的强化练习编程实验:

  1 #include <iostream>
  2 #include <string>
  3 
  4 using namespace std;
  5 
  6 class Memory
  7 {
  8 public:
  9     Memory()
 10     {
 11         cout << "Memory()" << endl;
 12     }
 13     ~Memory()
 14     {
 15         cout << "~Memory()" << endl;
 16     }
 17 };
 18 
 19 class Disk
 20 {
 21 public:
 22     Disk()
 23     {
 24         cout << "Disk()" << endl;
 25     }
 26     ~Disk()
 27     {
 28         cout << "~Disk()" << endl;
 29     }   
 30 };
 31 
 32 class CPU
 33 {
 34 public:
 35     CPU()
 36     {
 37         cout << "CPU()" << endl;
 38     }
 39     ~CPU()
 40     {
 41         cout << "~CPU()" << endl;
 42     }    
 43 };
 44 
 45 class MainBoard
 46 {
 47 public:
 48     MainBoard()
 49     {
 50         cout << "MainBoard()" << endl;
 51     }
 52     ~MainBoard()
 53     {
 54         cout << "~MainBoard()" << endl;
 55     }    
 56 };
 57 
 58 class Computer
 59 {
 60     Memory mMem;
 61     Disk mDisk;
 62     CPU mCPU;
 63     MainBoard mMainBoard;
 64 public:
 65     Computer()
 66     {
 67         cout << "Computer()" << endl;
 68     }
 69     void power()
 70     {
 71         cout << "power()" << endl;
 72     }
 73     void reset()
 74     {
 75         cout << "reset()" << endl;
 76     }
 77     ~Computer()
 78     {
 79         cout << "~Computer()" << endl;
 80     }
 81 };
 82 
 83 class HPBook : public Computer  // 要继承
 84 {
 85     string mOS;
 86 public:
 87     HPBook()  // 先调用父类的类成员构造函数,再调用父类的构造函数,再调用自身的构造函数;
 88     {
 89         mOS = "Windows 8";  // 出厂预装的 Windouw 8;
 90     }
 91     
 92     void install(string os)  // 添加新功能,安装操作系统
 93     {
 94         mOS = os;
 95     }
 96     
 97     void OS()  // 添加新功能,查看安装的系统
 98     {
 99         cout << mOS << endl;
100     }
101 };
102 
103 class MacBook : public Computer  // 要继承
104 {
105 public:
106     void OS()
107     {
108         cout << "Mac OS" << endl;
109     }
110 };
111 
112 int main()
113 {   
114     HPBook hp;
115     
116     hp.power();
117     hp.install("Ubuntu 16.04 LTS");
118     hp.OS();
119     
120     cout << endl;
121     
122     MacBook mac;
123     
124     mac.OS();
125     
126     return 0;
127 }

   

17,小结:

    1,继承是面向对象中类之间的一种关系;

    2,子类拥有父类的所有属性和行为;

    3,子类对象可以当作父类对象使用;

    4,子类中可以添加父类没有的方法和属性;

    5,继承是面向对象中代码复用的重要手段;

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇[NOI2006] 网络收费 下一篇C++中前置操作符和后置操作符的重..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目