继承与组合过程中构造函数和析构函数的调用顺序


#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析构函数 \n";
	}
protected:
	int a;
	int b;
};


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

	void printP(int a, int b)
	{
		cout << "我是爹..." << endl;
	}

protected:
	char *p;

};


class child : public Parent
{
public:
	child(char*p, char*p2) :Parent(p2), obj1(1, 2), obj2(3,4)
	{
		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("继承测试","shishenm");
}
void main()
{
	objplay();
	cout << "hello..." << endl;
	system("pause");
	return;
}
/*
在VC++6.0中的结果是:
---------------------------------------------
object构造函数 执行 a=1 b= 2
父类构造函数...shishenm
object构造函数 执行 a=1 b= 2
object构造函数 执行 a=3 b= 4
子类的构造函数继承测试
子类的析构继承测试
object析构函数
object析构函数
析构函数...shishenm
object析构函数
hello...
请按任意键继续. . .


结论:
先构造父类,再构造成员变量、最后构造自己
先析构自己,在析构成员变量、最后析构父类
//先构造的对象,后释放


---------------------------------------------
*/

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89205595
今日推荐