继承与组合混搭情况下,构造和析构调用原则

来源:互联网 发布:打开软件速度慢 编辑:程序博客网 时间:2024/05/19 17:25

原则:

  先构造父类,再构造成员变量、最后构造自己

  先析构自己,在析构成员变量、最后析构父类

//先构造的对象,后释放

案例:

#include <iostream>using namespace std;class Object{public:Object(int a,int b){this->a = a;this->b = b;cout<<"Object"<<a<<":"<<b<<endl;}~Object(){cout<<"~Object"<<endl;}protected:int a;int b;private:};class Parent:public Object{public:Parent(char*pp):Object(6,7){this->pp = pp;cout<<"Parent"<<pp<<endl;}~Parent(){cout<<"Parent析构函数"<<endl;}void print(){cout<<endl;}protected:char *pp;private:};class Child :public Parent{public:Child(char*pc):Parent("abcd"),o1(1,2),o2(3,4){this->pc = pc;cout<<"Child"<<pc<<endl;}~Child(){cout<<"Child析构函数"<<endl;}protected:char* pc;Object o2;Object o1;};void display(){Child c("abc123");}int main(){display();system("pause");return 0;}


0 0
原创粉丝点击