46-继承中的构造与析构
【问题】如何初始化父类成员?父类构造函数和子类构造函数有什么关系?
子类对象的构造
- 子类中可以定义构造函数
必须对继承而来的成员进行初始化:
- 直接通过初始化列表或者赋值的方式进行初始化
- 调用父类构造函数进行初始化
父类构造函数在子类中调用方式:
- 默认调用:适用于无参构造函数和使用默认参数的构造函数
- 显示调用:(1)通过初始化列表进行调用(2)适用于所有父类构造函数
父类构造函数的调用:
class Child : public Parent {
public:
Child() { /* 隐式调用 */
cout << "Child()" << endl;
}
Child(string s) : Parent("Parameter to Parent") { /* 显示调用 */
cout << "Child() : " << s << endl;
}
};
【范例代码】子类的构造函数
#include <iostream>
#include <string>
using namespace std;
class Parent {
public:
Parent() {
cout << "Parent()" << endl;
}
Parent(string s) {
cout << "Parent(string s) : " << s << endl;
}
};
class Child : public Parent {
public:
Child() {
cout << "Child()" << endl;
}
Child(string s) : Parent(s) {
cout << "Child(string s) : " << s << endl;
}
};
int main(int argc, const char* argv[]) {
Child c;
Child cc("cc");
return 0;
}
构造规则:
- 子类对象在创建时会首先调用父类的构造函数
- 先执行父类构造函数再执行子类的成员对象的构造函数(如果有),最后执行子类的构造函数
- 父类构造函数可以被隐式调用或者显示调用
【范例代码】子类构造深度解析
#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(int argc, const char* argv[]) {
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() : " << ms << 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() : " << ms << 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() " << ms << endl;
}
};
int main(int argc, const char* argv[]) {
Child cc("cc");
cout << endl;
return 0;
}