1.当父类的构造函数有参数时,需要在子类的初始化列表中显式调用。
2.析构函数调用的先后顺序与构造函数相反。
//继承时,构造和析构的顺序:先父母,再客人,后自己
#include <iostream>
using namespace std;
class Object
{
public:
Object(const char* s)
{
cout << "Object(): " << s << endl;
}
~Object()
{
cout << "~Object() " << endl;
}
};
class Parent : public Object
{
public:
Parent(const char* s):Object(s)
{
cout << "Parent() " << s << endl;
}
~Parent()
{
cout << "~Parent()" << endl;
}
};
class Child : public Parent
{
protected:
Object o1;
Object o2;
public:
Child():o2("o2"),o1("o1"),Parent("parent")
{
cout << "Child() " << endl;
}
~Child()
{
cout << "~Child() " << endl;
}
};
int main()
{
Child c;
cout << "----end----" << endl;
return 0;
}
/*
Object(): parent
Parent() parent
Object(): o1
Object(): o2
Child()
----end----
~Child()
~Object()
~Object()
~Parent()
~Object()
*/