子类调用父类构造函数和析构函数的顺序

来源:互联网 发布:js代码的运行过程 编辑:程序博客网 时间:2024/05/16 11:24

#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();

  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.

  ////////////////////////////////////////////

  构造函数调用父类-》子类;析构函数调用子类-》父类

原创粉丝点击