#include<iostream>
using namespace std;
class Parent
{
public:
Parent()
{
cout << "Parent()..." << endl;
a = 0;
}
Parent(int a)
{
cout << "Parent(int)..." << endl;
this->a = a;
}
~Parent() {
cout << "~Parent()......" << endl;
}
int a;
private:
};
class Child :public Parent
{
public:
//在调用子类的构造函数的时候,一定会调用父类的构造函数
//父类先构造,子类后构造
Child(int a,int b) :Parent(a)//不写,会调用无参构造(一般写出来)
{
cout << "Child(int,int)......" << endl;
this->b = b;
}
void printC()
{
cout << "b = " << b << endl;
}
~Child() {
cout << "~Child()......" << endl;
}
int b;
};
int main()
{
Child c(10,20);
c.printC();
cout << "" << endl;
return 0;
}
总结:
在调用子类的构造函数的时候,一定会调用父类的构造函数
父类先构造,子类后构造
先析构子类构造,再析构父类构造