您的位置:首页 > 编程语言 > C语言/C++

C++继承之构造析构函数调用

2016-06-24 17:11 351 查看
转载:http://www.cnblogs.com/kzloser/archive/2012/07/02/2570887.html
虚基类子对象是由最派生类的构造函数通过调用虚基类的构造函数进行初始化的.
最派生类是指在继承结构中建立对象时所指定的类.
在派生类的构造函数的成员初始化列表中,必须列出对虚基类构造函数的调用,如果没有列出,则表示使用该虚基类的缺省构造函数.
在虚基类直接或间接派生的派生类中的构造函数的成员初始化列表中,都要列出对虚基类构造函数的调用.但只有用于建立对象的最派生类的构造函数调用虚基类的构造函数,而该派生类的所有基类中列出的对虚基类构造函数的调用在执行中被忽略,从而保证对虚基类子对象只初始化一次.

在一个成员初始化列表中,同时出现对虚基类和非虚基类构造函数的调用时,基类的构造函数先于非虚基类的构造函数执行
#include <iostream>
#include <string>
using namespace std;

class A{
public:
A(){cout<<"A::A()    ";}
~A(){cout<<"A::~A()"<<endl;}
};
class B:virtual public A{
public:
B(){cout<<"B::B()    ";}
~B(){cout<<"B::~B()    ";}
};
class C:virtual public A{
public:
C(){cout<<"C::C()    ";}
~C(){cout<<"C::~C()    ";}
};
class D:public B,public C{
public:
D(){cout<<"D::D()"<<endl;}
~D(){cout<<"D::~D()    ";}
};
void funcD()
{
cout<<"this is class D:"<<endl;
cout<<"the order of constructor:    ";
D d;
cout<<"the order of destructor:    ";
}
int main()
{
funcD();
cout<<endl;
return 0;
}

结果:this is class D:
the order of constructor:    A::A()    B::B()    C::C()    D::D()
the order of destructor:    D::~D()    C::~C()    B::~B()    A::~A()

也可在派生类构造函数中调用基类构造函数;

#include <iostream>
#include <string>
using namespace std;

class A{
public:
A(){cout<<"A::A()    ";}
~A(){cout<<"A::~A()"<<endl;}
};
class B:virtual public A{
public:
B(){cout<<"B::B()    ";}
~B(){cout<<"B::~B()    ";}
};
class C:virtual public A{
public:
C(){cout<<"C::C()    ";}
~C(){cout<<"C::~C()    ";}
};
class D:public B,public C{
public:
D():C(),B(){cout<<"D::D()"<<endl;}
~D(){cout<<"D::~D()    ";}
};
class E:public C,public B
{
public:
E():C(),B(){cout<<"E::E()"<<endl;}
~E(){cout<<"E::~E()    ";}
};
void funcD()
{
cout<<"this is class D:"<<endl;
cout<<"the order of constructor:    ";
D d;
cout<<"the order of destructor:    ";
}
void funcE()
{
cout<<"this is class E:"<<endl;
cout<<"the order of constructor:    ";
E e;
cout<<"the order of destructor:    ";
}
int main()
{
funcD();
cout<<endl;
funcE();
cout<<endl;
return 0;
}
结果:this is class D:

the order of constructor:    A::A()    B::B()    C::C()    D::D()

the order of destructor:    D::~D()    C::~C()    B::~B()    A::~A()

this is class E:

the order of constructor:    A::A()    C::C()    B::B()    E::E()

the order of destructor:    E::~E()    B::~B()    C::~C()    A::~A()

由此可以看出,构造函数的顺序与继承顺序有关,而不是基类构造函数的调用有关,若基类使用默认的构造函数或不带参数的构造函数,则在派生类中定义定义构造函数时可略去对基类构造函数的调用“:基类构造函数(参数列表)”。对于析构函数,基类和派生类没有联系,不管派生类有没析构函数,基类的析构函数都会执行,且不用在派生类中调用基类的析构函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: