c++06

类之间的关系

大体上分为:纵向关系,横向关系

纵向关系就是继承关系

横向关系大体分为4种:

  • 依赖
  • 关联
  • 聚合
  • 组合

他们的强弱关系:依赖<关联<聚合<组合

组合

#include<iostream>
using namespace std;



class Hand
{
public:
	void Say()
	{
		cout << "hello" << endl;
	}
};

class Head
{
public:
	void Move()
	{
		cout << "move" << endl;
	}
};

class Person
{
private:
	Head a;
	Hand b;
public:
	void Meeting()
	{
		a.Move();
		b.Say();
	}
};



int main()
{
	Person ps;
	ps.Meeting();




	system("pause");
	return 0;
}

关联

#include<iostream>
using namespace std;


class Friend
{
public:
	int rp;
public:
	void Play()
	{
		cout << "带兄弟" << endl;
	}
};

class Person
{
private:
	Friend* pFriend;
public:
	Person()
	{
		pFriend = NULL;
	}
public:
	void SetFriend(Friend* pFriend)
	{
		if (pFriend->rp > 60)
		{
			this->pFriend = pFriend;
		}
	}
	void Play()
	{
		//有朋友
		if (this->pFriend != NULL)
		{
			cout << "双排" << endl;
		}
		//没有朋友
		else
		{
			cout << "单排" << endl;
		}
	}
};


int main()
{
	Friend *p = new Friend;
	Person ps;

	p->rp = 80;
	p->Play();
	ps.SetFriend(p);
	ps.Play();


	system("pause");
	return 0;
}

依赖

#include<iostream>
using namespace std;

class Computer
{
public:
	void Debug()
	{
		cout << "正在运行" << endl;
	}
};
class Person
{
public:
	void Code(Computer& cp)
	{
		cout << "打字中" << endl;
		cp.Debug();
	}
};

int main()
{
	Computer cp;
	Person ps;

	ps.Code(cp);


	system("pause");
	return 0;
}

聚合

#include<iostream>
using namespace std;

class Person
{
public:
	void Play()
	{
		cout << "haihai" << endl;
	}
};



class Family
{
public:
	Person* pArr[10];
public:
	Family()
	{
		for (int i = 0; i < 10; i++)
		{
			pArr[i] = NULL;//为了在play函数中判断是否为空 所以都先赋值为空
		}
	}
public:
	void PushPerson(Person *ps)
	{
		for (int i = 0; i < 10; i++)
		{
			if (pArr[i] == NULL)
			{
				pArr[i] = ps;
				break;
			}
		}
	}
	void Play()
	{
		for (int i = 0; i < 10; i++)
		{
			if (pArr[i] != NULL)
			{
				pArr[i]->Play();
			}
			else
			{
				cout << "---NULL---" << endl;
			}
		}
	}
	

};



int main()
{
	Family fa;
	Person ps1;
	Person ps2;
	Person ps3;
	Person ps4;
	 
	fa.PushPerson(&ps1);
	fa.PushPerson(&ps2);

	fa.Play();
	cout << "----------------------" << endl;
	
	fa.PushPerson(&ps3);
	fa.PushPer son(&ps4);
	fa.Play();


	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值