1.子类对象的构造
- 子类中可以定义构造函数
- 子类构造函数,必须对继承而来的成员进行初始化,有两种方式
- 调用父类构造函数进行初始化
- 直接通过初始化列表进行初始化或赋值的方式进行初始化
- 父类构造函数在子类中调用方式
- 默认调用:适用于无参构造函数和使用默认参数的构造函数
- 显式调用:通过初始化列表进行调用,适用于所有父类构造函数
class Child : public Parent
{
public:
Child()
{ //隐式调用
cout<<"Child()" <<endl;
}
Child(string s) : Parent("Parameter to Parent")
{//显示调用
cout<<"Child()" << s << endl;
}
};
2.编程实验
#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) // 在初始化列表中显示调用父类带参的Parent(string s)构造函数,如果不显示调用,则会默认调用父类无参的Parent()构造函数
{
cout << "Child(string s) :" << s << endl;
}
};
int main()
{
Child c;
Child cc("cc");
system("pause");
return 0;
}
- 运行结果:
3.构造规则
- 子类对象在创建时会首先调用父类的构造函数
- 先执行父类构造函数,再执行子类的构造函数
- 父类构造函数可以被隐式调用或显式调用
4.对象创建时构造函数的调用顺序(口决:先父母、后客人,再自己)
- 先调用父类的构造函数
- 再调用成员变量的构造函数(注意,这里的顺序与成员变量声明顺序相同!)
- 最后调用类自身的构造函数
4.析构函数的调用顺序与构造函数相反
- 先执行自身的析构函数
- 再执行成员变量的析构函数
- 最后执行父类的析构函数
5.对象的构造和析构深度解析
#include <iostream>
#include <string>
using namespace std;
class Object
{
string ms;
public:
Object(string s)
{
cout << "Object(string s) :" << s << endl;
}
~Object()
{
cout << "~Object(): =" << ms << endl;
}
};
class Parent : public Object
{
string ms;
public:
Parent() : Object("Default") // 必须显示调用,因为父类Object没有提供无参构造函数,
// 而默认只会调用无参构造函数。如果不指定他的调用就会报错
{
ms = "Default";
cout << "Parent()" << endl;
}
Parent(string s) : Object(s) // 有参构造函数
{
cout << "Parent(string s) :" << s << endl;
}
~Parent()
{
cout << "~Parent(): =" << ms << endl;
}
};
class Child : public Parent
{
Object mo1;
Object mo2;
string ms;
public:
Child() : mo1("Default 1"), mo2("Default 2")
{
ms = "Default";
cout << "Child()" << endl;
}
Child(string s) : Parent(s), mo1(s + "1"), mo2(s + "2")
{
ms = s;
cout << "Child(string s) :" << s << endl;
}
~Child()
{
cout << "~Child(): " << ms << endl;
}
};
void run()
{
Child cc("cc"); // //先父类,后客人,再自己,初始化列表中按声明的顺序。析构相反
}
int main()
{
run();
system("pause");
return 0;
}
- 运行结果
5.总结
- 子类对象在创建时需要调用父类构造函数进行初始化
- 先执行父类构造函数然后执行成员的构造函数
- 父类构造函数显示调用需要在初始化列表中进行
- 子类对象在销毁时需要调用父类解析函数进行清理
- 析构顺序与构造顺序对称相反