1、 在子类对象构造时,需要调用父类构造函数对其继承得来的成员进行初始化
2、 在子类对象析构时,需要调用父类析构函数对其继承得来的成员进行清理
//继承中的构造析构调用原则 // 构造函数执行顺序: //1:先执行父类的构造函数 //2:再执行子类的构造函数 //析构函数执行顺序 //1:先执行子类析构函数 //2:再执行父类析构函数 函数如何调用呢? Child(int a,int b,int c) : Parent(a,b) #include<iostream> using namespace std; //继承中的构造析构调用原则 // 构造函数执行顺序: //1:先执行父类的构造函数 //2:再执行子类的构造函数 //析构函数执行顺序 //1:先执行子类析构函数 //2:再执行父类析构函数 //子类构造函数应该变化的地方 //Child(int a,int b,int c) : Parent(a,b) /* 继承中的构造析构调用原则 1、子类对象在创建时会首先调用父类的构造函数 2、父类构造函数执行结束后,执行子类的构造函数 3、当父类的构造函数有参数时,需要在子类的初始化列表中显示调用 4、析构函数调用的先后顺序与构造函数相反 */ class Parent { public: Parent(int a,int b) { this->a = a; this->b = b; cout<<"父类构造函数"<<endl; } ~Parent() { cout<<"父类析造函数"<<endl; } void printP(int a,int b) { this->a = a; this->b = b; cout<<"我是爹"<<endl; } protected: private: int a; int b; }; class Child :public Parent { public: //变化的地方 Child(int a,int b,int c) : Parent(a,b) { this->c = c; cout<<"子类构造函数"<<endl; } ~Child() { cout<<"子类析造函数"<<endl; } void printC() { cout<<"我是儿子"<<endl; } protected: private: int c; }; void playObj() { Child c1(1,2,3); } int main() { /*Parent p(1,2);*/ playObj(); system("pause"); return 0; }