特别注意:
由于派生类不能继承基类的构造函数和析构函数,因此派生类需要写构造函数,如果基类里的构造函数里没有参数,那么派生类里就不需要写入构造函数,系统会自动调用基类和派生类的构造函数完成初始化,如果基类的构造函数里有参数,则派生类里就需要根据基类的构造函数的参数进行设置,首先初始化基类的数据成员,然后初始化基类的对象,然后再初始化派生类的数据成员,而析构函数与构造函数的调用顺序相反,
构造函数的调用顺序:按照派生类继承的顺序从左到右,然后调用继承的类的对象的构造函数,按照继承的对象在派生类的声明顺序,最后调用派生类的构造函数,析构函数按相反的顺序调用⋯⋯本文结尾附有运行结果。
#include
using namespace std;
class A
{
public:
A(int a,int b)
{
static int i=0;
i++;
cout<<"A类的构造函数被调用"<<i<<"次"<<"\n";
this->a = a;
this->b = b;
cout<<"a="<<a<<"\n";
cout<<"b="<<b<<"\n";
}
int geta()
{
return a;
}
int getb()
{
return b;
}
~A()
{
static int j=0;
j++;
cout<<"A类的析构函数被调用"<<j<<"次"<<"\n";
}
private:
int a,b;
};
class C
{
private:
int z,l;
public:
C(int z,int l)
{
static int m=0;
m++;
cout<<"C类的构造函数被调用"<<m<<"次"<<"\n";
this->z=z;
this->l=l;
cout<<"z="<<z<<"\n";
cout<<"l="<<l<<"\n";
}
~C()
{
static int t=0;
t++;
cout<<"C类的析构函数被调用"<<t<<"次"<<"\n";
}
};
class B:public A,public C
{
public:
B(int x,int y,int z,int w):A(x,y),s(z,w),d(z,w),C(x,y)
{
static int m=0;
m++;
cout<<"B类的构造函数被调用"<<m<<"次"<<"\n";
this->x = x;
this->y = y;
}
void print()
{
cout<<"x="<<x<<"\n";
cout<<"y="<<y<<"\n";
}
~B()
{
static int t=0;
t++;
cout<<"B类的析构函数被调用"<<t<<"次"<<"\n";
}
private:
int x,y;
A s;
C d;
};
int main (int argc, const char * argv[])
{
// insert code here...
B b(1,2,3,4);
b.print();
return 0;
}
A类的构造函数被调用1次
a=1
b=2
C类的构造函数被调用1次
z=1
l=2
A类的构造函数被调用2次
a=3
b=4
C类的构造函数被调用2次
z=3
l=4
B类的构造函数被调用1次
x=1
y=2
B类的析构函数被调用1次
C类的析构函数被调用1次
A类的析构函数被调用1次
C类的析构函数被调用2次
A类的析构函数被调用2次