cc28a_demo-派生类的构造函数和析构函数-代码示范

//派生类的构造函数和析构函数
//派生类的构造函数(执行步骤)
//--执行基类的构造函数
//--执行成员对象的构造函数
//--执行派生类的构造函数

//父类,子类
//构造函数与析构函数不能继承

//派生类的析构函数
//--对派生类新增普通成员进行清理
//--调用成员对象的析构函数
//--调用基类析构函数

没有看到析构执行过程,参考如下链接

https://blog.csdn.net/txwtech/article/details/103978929

//派生类的构造函数和析构函数
//派生类的构造函数(执行步骤)
//--执行基类的构造函数
//--执行成员对象的构造函数
//--执行派生类的构造函数

//父类,子类
//构造函数与析构函数不能继承

//派生类的析构函数
//--对派生类新增普通成员进行清理
//--调用成员对象的析构函数
//--调用基类析构函数
#include <iostream>
using namespace std;
class 老子
{
	//成员:
public:
	int X;
};
class 小子 :public 老子
{
	//新的成员
public:
	int Y;
};
class Base1
{
public: 
	Base1(int i)
	{
		b1 = i;
		cout << "base1的构造函数被调用" << endl;
	}
	void Print() const
	{
		cout << b1 << endl;
	}
private:
	int b1;
};
class Base2
{
public:
	Base2(int i)
	{
		b2 = i;
		cout << "base2的构造函数被调用" << endl;
	}
	void Print()
	{
		cout << b2 << endl;
	}
private:
	int b2;
};
class Base3
{
public:
	Base3()
	{
		b3 = 0;
		cout << "Base3缺省的构造函数被调用。" << endl;

	}
	void Print()
	{
		cout << b3 << endl;
	}
private:
	int b3;
};
//小子,派生类
class Member
{
public:
	Member(int i)
	{
		m = i;
		cout << "Member的构造函数被调用:" << endl;
	}
	int GetM()
	{
		return m;
	}
private:
	int m;
};
class Derived :public Base2, public Base1, public Base3
{
public:
	Derived(int i, int j, int k, int l);
	void Print();

private:
	int d;
	Member mem;
};
Derived::Derived(int i, int j, int k, int l):Base1(i),Base2(j),mem(k)
{
	d = l;
	cout << "Derived的构造函数被调用。" << endl;
}
void Derived::Print()
{
	Base1::Print();
	Base2::Print();
	Base3::Print();
	cout << mem.GetM() << endl;
	cout << d << endl;
}

int main()
{
	小子 a; //a是一个小子,创建小子对象,必须先创建/构造老子
	a.X = 1;
	a.Y = 2;
	//cout << "hello111" << endl;
	Derived obj(1,2,3,4);
	obj.Print();
	getchar();
	return 0;
}
#include <iostream>//txwtech,派生类的构造函数与析构函数2

using namespace std;

class Base
{
public:
	Base()
	{
		b1 = b2=0;
	}
	Base(int i, int j);
	~Base();
	void Print()
	{
		cout << b1 << "," << b2 << ",";//<<endl;
	}

private:
	int b1, b2;

};
Base::Base(int i, int j)
{
	b1 = i;
	b2 = j;
	cout << "Base的构造函数被调用:" << b1 << "," << b2 << endl;
}
Base::~Base()
{
	cout << "析构函数被调用: " << b1 << "," << b2 << endl;
}
class Derived :public Base
{
public:
	Derived()
	{
		d = 0;
	}
	Derived(int i, int j, int k);
	~Derived();
	void Print();
private:
	int d;
};
Derived::Derived(int i, int j, int k) :Base(i, j), d(k)
{
	cout << "derived的构造函数被调用:" << d << endl;
}
Derived::~Derived()//派生类的析构函数
{
	cout << "Derived的析构函数被调用咯:" << d << endl;
}
void Derived::Print()
{
	Base::Print();
	cout << d << endl;
}


int main()
{

	Derived objD1(1,2,3),objD2(-4,-5,-6);
	objD1.Print();
	objD2.Print();
	//system("pause");
	//getchar();
	return 0;
}
发布了356 篇原创文章 · 获赞 186 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/txwtech/article/details/103979659