组合类简单点讲就是A类中有B类,B类定义在A类外面。比如点类和圆类,圆类就可以设计成组合类。因为外部程序会用到点对象,也会用到圆对象,所以可以将圆类设计成组合类。
组合类设计代码实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
//============================================================================ // Author : 梁笔记 // Copyright : https://zouzhongliang.com //============================================================================ #include <iostream> using namespace std; class Point { private: double x; double y; public: Point() { x=0; y=0; } Point(double x,double y) { this->x=x; this->y=y; } ~Point(){} }; class Circle { private: double Radius; Point Center; public: Circle(double Radius, Point Center) { this->Radius = Radius; this->Center = Center; } ~Circle(){} }; int main() { Point p1(10,20); //点对象 Point p2(20,30); //点对象 Circle(5,p1);//圆对象 Circle(5,p2);//圆对象 return 0; } |
嵌套类就是A类中有B类,B类定义在A类里面。这种就有了从属关系,要单独定义B类就必须要写成A::B b(B定义在A类中公有的public部份),这种可以看成多了一层名字空间,但这不是主要目的。一般来说B类如果只属于A类,外部几乎不会用到B类,这种情况下就会设计成设计成嵌套类。对类进行嵌套通常是为了帮助实现另一个类,并避免名称冲突。
组合类设计实例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
//============================================================================ // Author : 梁笔记 // Copyright : https://zouzhongliang.com //============================================================================ #include <iostream> using namespace std; class Circle { private: double Radius; class Point { public: double x; double y; } Center; public: Circle(double Radius, double x,double y ) { this->Radius = Radius; this->Center.x = x; this->Center.y = y; } ~Circle(){} }; int main() { Circle(5,10,20);//圆对象 return 0; } |
这样将点类设计到圆类里,还有一个好处,减少圆类对外部依赖项。依赖问题在做大的项目时比较常见到。
注:理解组合类和嵌套类的本质后,根据实际编程需要来运用。组合类和嵌套类其本身来讲没有好坏之分,初学者不要认为组合类优于嵌套类,或是嵌套类优于组合类。如果一定要比较,哪就是必须有实际的设计需求。
Whoa plenty of awesome info! fluconazole bnf
You actually said it terrifically. generic viagra price at walmart
Truly lots of awesome information! https://viagrapython.com/
Incredible all kinds of terrific data! viagra without a doctor prescription texas
Awesome material, Kudos! buy cialis online
Good info. Thank you! https://viagradocker.com/
You actually explained that really well. https://viagrapython.com/
Awesome material. Thank you! canada drug
Cheers! Helpful information. Generic Name For Lasix Medication
You revealed this wonderfully. kratom for sale
Effectively expressed really! . canadian pharmacies without an rx
Thank you, A lot of material.
pharmacies in canada
Good info. Thanks! how to enhance viagra effects
With thanks! I like it! generic viagra without a doctor prescription
Many thanks. Helpful stuff. canadian pharmacy
Nicely put. Appreciate it! doxycycline mono 100mg cap
You actually suggested that effectively! american eagle cbd
Kudos! Loads of stuff!
mexican pharmacies shipping to usa
Seriously many of great advice! furosemide 40 mg tablet
You have made your point quite nicely.. kratom for sale