派生类的构造函数

#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()
	{
		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(int i)
	{
		b3 = i;
		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),Base3(k), 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;

	Derived obj(1,2,3,4); // obj就是一个对象,原来是没有的,现在有了,
	obj.Print();

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值