类之间的关系
大体上分为:纵向关系,横向关系
纵向关系就是继承关系
横向关系大体分为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;
}