主页 > 软件开发  > 

C++:类之间的关系

C++:类之间的关系

类与类的关系分为纵向关系和横向关系,纵向关系即为继承关系(后续帖子会有介绍),横向关系大体上可分为四种:依赖,关联,聚合,组合(此顺序为关系由弱到强,即依赖最弱)。

下面我们来介绍一下这几个关系。

1.依赖

所谓依赖就是类A使用了类B,但这种使用是偶然的,暂时的,但B的变化会影响到A。比如我要敲代码,就要使用到电脑,那么我与电脑之间就是依赖关系。在代码方面表现为电脑类作为参数被我类在某方法中使用,如:

#include<iostream> using namespace std; class Computer { public: void Debug() { cout << "#include..." << endl; } }; class Person { public: void Code(Computer* pCom) { cout << "小手劈里啪啦打代码" << endl; pCom->Debug(); } }; int main() { Person ps; Computer pCom; ps.Code(&pCom); return 0; }

UML类图:

2.关联

比依赖更强,不存在依赖的偶然性,一般都是长期的且双方关系平等,例如我和我的朋友。

在代码方面表现为被关联类以类的属性形式出现在关联类中或者关联类引用了一个类型为被关联类的全局变量,如:

#include<iostream> using namespace std; class Friend { public: int nRp; public: Friend(int nRp) { this->nRp = nRp; } public: void Play() { cout << "文能挂机喷队友,武能越塔送人头" << endl; } }; class Person { private: Friend* pFriend; public: Person() { pFriend = NULL; } public: void SetFriend(Friend* pFriend) { if (pFriend->nRp > 60) { this->pFriend = pFriend; } else { cout << "人品不行" << endl; } } void Play() { if (pFriend != NULL) { pFriend->Play(); cout << "真坑啊" << endl; } else { cout << "自己玩没意思" << endl; } } }; int main() { Friend f(80); Person ps; ps.SetFriend(&f); ps.Play(); return 0; }

UML类图:

3.聚合

聚合是关联的特例,它类似于一种包含,如公司与员工,家庭与家人,它体现的是整体与部分的关系,整体与部分是可以分离的,可以具有不同的生命周期,部分可以属于多个整体。

#include<iostream> using namespace std; class Person { public: void Play() { cout << "摇起来" << endl; } }; class Family { public: Person* arr[10]; public: Family() { for (int i = 0; i < 10; i++) { arr[i] = NULL; } } public: void PushPerson(Person* pPs) { for (int i = 0; i < 10; i++) { if(arr[i] == NULL ) { arr[i] = pPs; return; } } cout << "没位置了" << endl; } void Play() { for (int i = 0; i < 10; i++) { if (arr[i] != NULL) { arr[i]->Play(); } else { cout << "---NULL---" << endl; } } } }; int main() { Person ps1,ps2,ps3; Family f; f.PushPerson(&ps1); f.PushPerson(&ps2); f.PushPerson(&ps3); f.Play(); return 0; }

UML类图:

4.组合

组合也是关联的特例,组合也称强聚合,与聚合不同的是,组合的部分与整体是不可分的,整体生命周期的结束也意味着部分的结束,如人和人的大脑之间就是组合关系。

#include<iostream> using namespace std; class Head { public: void Say() { cout << "哔哔赖赖" << endl; } }; class Hand { public: void Move() { cout << "比比划划" << endl; } }; class Person { private: Head head; Hand hand; public: void Meeting() { head.Say(); hand.Move(); } }; int main() { Person ps; ps.Meeting(); return 0; }

UML类图:

标签:

C++:类之间的关系由讯客互联软件开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“C++:类之间的关系