构造函数和析构函数解析

来源:互联网 发布:maxdos网络克隆教程 编辑:程序博客网 时间:2024/06/04 19:13

1、构造函数

1.1、构造函数的执行顺序

子类会自动调用父类的默认构造函数;

如果父类中没有默认构造函数,子类又没有显示声明调用( 如Son():Super(1) ),会提示错误。

 

构造函数顺序如下:

1、 如果有基类则首先构造基类;

      1)调用顺序仅仅和继承声明时一致,

      2)不管是否在子类的构造函数实现时给出显示调用,例如Child(int i) : Parent2(i),Parent1(i) ;     

      3) 如果构造函数定义后给出了调用方式,就不调用默认的构造函数,而是按照给出的方式构造,但是顺序还是按照上面所说。

             例如Child(int i) :member1(1), member2(2) ,Parent2(i),Parent1(i) 定义,则调用给出的有参构造函数;

2、 非static数据成员按照声明顺序构造;

       不管是否在子类的构造函数中给出显示调用,例如 Child(int i) : something2(i),something1(i);

3、 执行构造函数体


1.2、构造函数是否有必要设置为虚函数(virtrual)

构造函数没必要设置为虚函数,因为创建对象时,类是明确的;而且默认会调用父类的构造函数。

 

 

2、析构函数

1.1、析构函数的执行顺序

子类会自动调用父类的析构函数;且和构造函数调用完全程逆序。

 

析构函数执行顺序和构造函数正好相反:

1、 调用自身的析构函数;

2、 按照构造的逆序删除数据成员;

3、 如果有父类,按照继承的逆序,删除父类。

1.2、析构函数是否有必要设置为虚函数(virtrual)

良好的习惯是,析构函数必须声明为虚函数;

这样在实现多态,销毁对象是,才会从真正对象的析构函数执行起;

否则父类指针指向子类对象,deelte时,只会执行父类的析构函数,造成内存泄漏;或者执行出错。

 

 

class Somethting1{public:Somethting1(){ cout<<"Somethting1 construct\n";}Somethting1(int i){ cout<<"Somethting1(int i) construct\n";}~Somethting1(){ cout<<"Somethting1 destructor\n";}};class Somethting2{public:Somethting2(){ cout<<"Somethting2 construct\n";}Somethting2(int i){ cout<<"Somethting2(int i) construct\n";}~Somethting2(){ cout<<"Somethting2 destructor\n";}};class Parent1{public:Parent1(){ cout<<"Parent1 construct\n";}Parent1(int i){ cout<<"Parent1(int i) construct\n";}~Parent1(){ cout<<"Parent1 destructor\n";}};class Parent2{public:Parent2(){ cout<<"Parent2 construct\n";}Parent2(int i){ cout<<"Parent2(int i) construct\n";}~Parent2(){ cout<<"Parent2 destructor\n";}};class Child : public Parent1, public Parent2{protected:Somethting1 something1;Somethting2 something2;public:Child(){ cout<<"Child construct\n";}Child(int i) : something2(i), something1(i),Parent2(i), Parent1(i) { cout<<"Child(int i) construct\n";}Child(int i, int j) { cout<<"Child(int i, int j) construct\n";}~Child(){ cout<<"Child destructor\n";}};<pre name="code" class="cpp">int main( int argc, char** argv){Child* p1 = new Child();delete(p1);cout<<"\n";Child* p2 = new Child(2);delete(p2);cout<<"\n";Child* p3 = new Child(1,2);delete(p3);cout<<"\n";return 0;}





0 0
原创粉丝点击