C++:继承中的构造函数和析构函数
1、继承中构造函数和析构函数调用顺序
a、调用父类构造函数;
b、调用其他成员的构造函数;
c、调用子类构造函数;
d、析构调用顺序相反。
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"Base中的默认构造函数调用"<<endl;
}
~Base()
{
cout<<"Base中的析构函数调用"<<endl;
}
};
class Other
{
public:
Other()
{
cout<<"Other中的默认构造函数调用"<<endl;
}
~Other()
{
cout<<"Other中的析构函数调用"<<endl;
}
};
class Son : Base
{
public:
Son()
{
cout<<"Son中的默认构造函数调用"<<endl;
}
~Son()
{
cout<<"Son中的析构函数调用"<<endl;
}
Other o;
};
int main()
{
Son s;
return 0;
}
2、子类默认调用父类的默认构造函数。因此父类须提供默认构造函数,否则子类须利用初始化列表方法显式调用父类的其他构造函数
#include <iostream>
using namespace std;
// 该类中仅提供了有参构造函数,无默认构造函数
class Base
{
public:
int m_A;
public:
Base(int var)
{
this->m_A = var;
cout<<"Base中的有参构造函数调用"<<endl;
}
};
class Son : public Base
{
public:
// 继承的父类Base中无默认构造函数,须利用初始化列表方法,显式调用父类其他构造函数。
explicit Son02(int a = 0): Base(a)
{
cout<<"Son中的有参构造函数调用"<<endl;
}
};
void test02(){
Son s;
cout<<s.m_A<<endl;
}
3、父类中的构造函数(默认、有参、拷贝)、析构及赋值运算符函数不会被子类继承