原则:先构造父类(如果父类还有父类,则先构造父类的父类),再构造成员变量(构造组合类),
最后构造自己;
先析构自己,再析构成员变量(析构组合类),最后析构父类,如果父类还有父类,继续析构
父类的父类。
示例代码:祖宗类Object,同时也是子类的组合类,父类Parent,子类Child
#include <iostream>
using namespace std;
class Object
{
public:
Object(int a, int b)
{
this->a = a;
this->b = b;
cout << "Object 构造函数执行" << "a" << a << "b" << b << endl;
}
~Object()
{
cout << "Object 析构函数" << endl;
}
protected:
int a;
int b;
prpivate:
}
class Parent : public Object
{
public:
Parent(char* p) : Object(1, 2)
{
this->p = p;
cout << "父类构造函数..." << endl;
}
~Parent()
{
cout << "析构函数" << endl;
}
void printP(int a, int b)
{
cout << "父类..." << endl;
}
protected:
char *p;
}
class Child : public Parent
{
public:
Child(char *p) : Parent(p), obj1(3, 4), obj2(5, 6)
{
this->myp = p;
cout << "子类的构造函数" << myp << endl;
}
~Child()
{
cout << "子类的析构函数" << myp << endl;
}
void printC()
{
cout << "子类..." << endl;
}
protected:
char *myp;
Object obj1;
Object obj2;
}
void objplay()
{
Child c1("继承测试");
}
int main()
{
objplay();
return 0;
}