继承当中的构造与析构
子类构造函数初始化
子类构造函数初始化
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
Parent()
{
cout << "Parent() :" << endl;
}
Parent(string s)
{
cout << "Parent(string s) :" << endl;
}
};
class Child : public Parent
{
public:
Child()
{
cout << "Child()" << endl;
}
Child(string s) : Parent(s)
{
cout << "Child(string s)" << endl;
}
};
int main()
{
Child c;
Child cc("cc");
return 0;
}
构造规则
- 子类创建对象时先会调用父类构造函数
- 先执行父类构造函数在执行子类构造函数
- 父类构造函数可以被隐式调用(无参或默认参数值函数)或显示调用(初始化列表)
对象创建构造函数的调用函数
- 1.调用父类的构造函数(父母)
- 2.调用成员变量的构造函数(他人)
- 3.调用自身类的构造函数(自己)
子类构造深度分析
#include <iostream>
#include <string>
using namespace std;
class Object
{
public:
Object(string s)
{
cout << "Object(string s):" << s << endl;
}
};
class Parent : public Object
{
public:
Parent() : Object("Default")
{
cout << "Parent() :" << endl;
}
Parent(string s) : Object(s)
{
cout << "Parent(string s) :" << s << endl;
}
};
class Child : public Parent
{
Object mO1;
Object mO2;
public:
Child() : mO1("Default 1"), mO2("Default 2")
{
cout << "Child()" << endl;
}
Child(string s) : Parent(s) , mO1(s + " 1") ,mO2(s + " 2")
{
cout << "Child(string s):" << s << endl;
}
};
int main()
{
Child cc("cc");
return 0;
}
析构函数调用顺序
#include <iostream>
#include <string>
using namespace std;
class Object
{
string ms;
public:
Object(string s)
{
cout << "Object(string s):" << s << endl;
ms = s;
}
~Object()
{
cout << "~Object():" << endl;
}
};
class Parent : public Object
{
string ms;
public:
Parent() : Object("Default")
{
cout << "Parent() :" << endl;
ms = "Default";
}
Parent(string s) : Object(s)
{
cout << "Parent(string s) :" << s << endl;
ms = s;
}
~Parent()
{
cout << "~Parent()" << endl;
}
};
class Child : public Parent
{
Object mO1;
Object mO2;
string ms;
public:
Child() : mO1("Default 1"), mO2("Default 2")
{
cout << "Child()" << endl;
ms = "Default";
}
Child(string s) : Parent(s) , mO1(s + " 1") ,mO2(s + " 2")
{
cout << "Child(string s):" << s << endl;
ms = s;
}
~Child()
{
cout << "~Child()" << endl;
}
};
int main()
{
Child cc("cc");
return 0;
}
小结
- 子类创建对象需要调用父类构造函数进行初始化
- 先执行父类构造函数后执行成员的构造函数
- 父类构造函数显示调用需要在初始化列表中进行
- 子类对象在销毁时需要调用父类析构函数进行清理
- 析构顺序与构造顺序对称相反