- 橫向關系
依賴 關聯 聚合 組合
判斷方法:
生命周期有關系:組合,聚合
聚合:包含多個相同的類
組合:定義的時候就要有
依賴:只要使用就必須要有
關聯:可有可無
- 縱向關系
繼承
基類( 父類 )->派生類(子類)
1 #include <iostream> 2 using namespace std; 3 4 class CPerson 5 { 6 protected: 7 8 public: 9 int age; 10 CPerson() 11 { 12 age = 100; 13 } 14 }; 15 class CSuperman :public CPerson 16 { 17 protected: 18 19 public: 20 int age; 21 CSuperman() 22 { 23 age = 123; 24 } 25 }; 26 int main() 27 { 28 CPerson person; 29 CSuperman superman; 30 cout<<superman.age<<endl; //123 31 cout<<superman.CPerson::age<<endl; //100 32 superman.CPerson::age = 111; 33 cout<<person.age<<endl;//改寫的為父類中的子類,與父類沒關系 //100 34 cout<<superman.CPerson::age<<endl; //111 35 }
??父類中?private?成員在無論怎樣繼承,在子類中都不可訪問public?繼承?public和protected?沒有變化protected??繼承??public?變成?protected?private????繼承???public,?protected?變成?private
繼承的構造和析構
1 #include<iostream> 2 using namespace std; 3 4 class AA 5 { 6 public: 7 AA() 8 { 9 cout << "AA" << endl; 10 } 11 ~AA() 12 { 13 cout << "~AA" << endl; 14 } 15 }; 16 17 class BB:public AA 18 { 19 public: 20 BB() 21 { 22 cout << "BB" << endl; 23 } 24 ~BB() 25 { 26 cout << "~BB" << endl; 27 } 28 }; 29 30 class CC 31 { 32 public: 33 CC() 34 { 35 cout << "CC" << endl; 36 } 37 ~CC() 38 { 39 cout << "~CC" << endl; 40 } 41 }; 42 43 class DD:public CC 44 { 45 public: 46 BB b; 47 public: 48 DD() 49 { 50 cout << "DD" << endl; 51 } 52 ~DD() 53 { 54 cout << "~DD" << endl; 55 } 56 }; 57 58 int main() 59 { 60 DD d; 61 62 return 0; 63 }