当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
子类调用父类构造函数和析构函数的顺序
发布时间:2010/6/2 15:39:58 来源:城市学习网 编辑:ziteng
  #include   <iostream.h>
  class   B
  {
  public:
  B(); //与类同名,构造函数
  B(int   i);
  ~B(); //~析构函数
  void   Print()   const;//const,常量成员,不能修改
  private:
  int   b;
  };
  B:B()
  {
  b=0;
  cout < < "B 's   default   constructor   called.   " < <endl;
  }
  B::B(int   i)
  {
  b=i;
  cout < < "B 's   constructor   called.   " < <endl;
  }
  B::~B()
  {
  cout < < "B 's   destructor   called.   " < <endl;
  }
  void   B:Print()   const
  {
  cout < <b < <endl;
  }
  class   C:public   B
  {
  public:
  C();
  C(int   i,int   j);
  ~C(); [NextPage]   void   Print()   const;
  private:
  int   c;
  };
  C::C()
  {
  c=0;
  cout < < "C 's   default   constructor   called.   " < <endl;
  }
  C::C(int   i,int   j):B(i)
  {
  c=j;
  cout < "C 's   constructor   called.   " < <endl;
  }
  C::~C()
  {
  cout < < "C 's   destructor   called.   " < <endl;
  }
  void   C::Print()   const
  {
  B::Print();
  cout < <c < <endl;
  }
  void     main()
  {
  C   obj(5,6);
  obj.Print();
  }
  输出:
  B 's   constructor   called.
  C 's   constructor   called.
  5
  6
  C 's   destructor   called.
  B 's   destructor   called.
  ////////////////////////////////////////////
  构造函数调用父类-》子类;析构函数调用子类-》父类
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved