继承和组合混搭下的构造和析构

#include<iostream>//30
#include<cstdlib>
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;
};

class Parent:public Object
{
public:
	Parent(char *p) :Object(1, 2)
	{
		this->p = p;
		cout << "Parent构造函数" << endl;
	}
	~Parent()
	{
		cout << "Parent析构函数" << endl;
	}
	void PrintP()
	{
		cout << "Parent" << endl;
	}
protected:
	char *p;
};

class Child :public Parent
{
public:
	Child(char *c) :Parent(c), obj1(1, 2), obj2(3, 4)
	{
		this->myc = c;
		cout << "Child构造函数" << endl;
	}
	~Child()
	{
		cout << "Child析构函数" << endl;
	}
protected:
	char *myc;
	Object obj1;
	Object obj2;
};
void playObj()
{
	Child c1("继承和组合混搭下的测试");
}
int main()
{
	playObj();

	system("pause");
	return 0;
}

//结果是:
//构造函数调用顺序:
//1.先调用父类构造函数(父类如果也有继承就最先调用老祖宗的构造函数)
//2.再调用组合对象Object的构造函数
//3.最后调用自己的构造函数
//
//析构顺序和构造顺序相反

发布了66 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/RitaAndWakaka/article/details/79832999