Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4273941
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-07-07 09:43:52

工程代码:  page40.rar  


    如果有 子类、父类,在初始化的时候,先 初始化父类的构造函数,然后子类的构造函数, 在析构的时候,先 析构 子类的析构函数,然后 父类的析构函数

    如果在父类构造函数中,需要有参数需要初始化,我们一定要在 子类构造函数中传递参数给父类构造函数

  1. #include <iostream>

  2. using namespace std;

  3. class animal //定义一个 动物类
  4. {
  5. public: //在类中 声明,内联函数
  6.         animal(int height, int width)// 无参构造函数
  7.         {
  8.             cout << "animal construct" << endl;
  9.         }

  10.         ~animal() //析构函数
  11.         {
  12.             cout << "animal destruct" << endl;
  13.         }

  14.         void eat()
  15.         {
  16.             cout << " animal eat" << endl;
  17.         }

  18.         void breathe()
  19.         {
  20.             cout << "animal breathe" << endl;
  21.         }
  22. };

  23. class fish : public animal //定义fish类 ,基于 animal类
  24. {
  25. public: //在声明子类时,先初始化 父类构造函数,然后初始化子类函数
  26.      //在父类构造函数中,需要 初始化 height width ,所以我们在
  27.      //子类中,需要传递参数给父类 构造函数
  28.         fish():animal(400,500) // 子类构造函数
  29.         {
  30.             cout << "fish construct" << endl;
  31.         }

  32.         ~fish()
  33.         {
  34.             cout << "fish destruct" << endl;
  35.         }
  36. };

  37. void main()
  38. {
  39.     fish fh;
  40. }

注意: 父类、子类 构造 析构 的顺序

       1. 父类 构造

       2. 子类 构造

       3. 子类 析构

       4. 父类 析构




阅读(851) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~