继承的作用以及在子类中初始化所有数据的方法
1.方便扩充程序,使之不必重写整个程序
代码示例
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 class father 5 { 6 protected: 7 string name; 8 int tall; 9 public: 10 father(string a, int i); 11 father(){ cout << "构造基类\n"; } 12 void print(){ cout << name << "身高为" << tall << "\n"; } 13 ~father(){ cout << "释放基类对象\n"; } 14 }; 15 /*-------------相当于原有程序的功能-------------*/ 16 father::father(string a, int i) 17 { 18 cout << "\n在基类的构造函数内\n"; 19 name = a; 20 tall = i; 21 print(); 22 cout << "离开基类构造函数\n"; 23 } 24 class son :public father 25 { 26 private: 27 int weight; 28 public: 29 son(string a, int i, int j); 30 void print1(); 31 ~son(){ cout << "\n释放子类对象\n"; } 32 }; 33 /*--------相当于在原有程序功能上增加了新的功能-----------*/ 34 son::son(string a, int i, int j) 35 { 36 name = a; 37 tall = i; 38 cout << "\n在子类构造函数中\n"; 39 weight = j; 40 } 41 void son::print1() 42 { 43 father::print(); 44 cout << "体重:" <<weight; 45 } 46 int main() 47 { 48 son a("Mike", 180, 80); 49 a.print1(); 50 cout << "\n结束了\n"; 51 return 0; 52 }
运行结果
方案二
代码示例
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 class father 5 { 6 protected: 7 string name; 8 int tall; 9 public: 10 father(string a, int i); 11 father(){ cout << "构造基类\n"; } 12 void print(){ cout << name << "身高为" << tall << "\n"; } 13 ~father(){ cout << "释放基类对象\n"; } 14 }; 15 /*-------------相当于原有程序的功能-------------*/ 16 father::father(string a, int i) 17 { 18 cout << "\n在基类的构造函数内\n"; 19 name = a; 20 tall = i; 21 print(); 22 cout << "离开基类构造函数\n"; 23 } 24 class son :public father 25 { 26 private: 27 int weight; 28 public: 29 son(string a, int i, int j); 30 void print1(); 31 ~son(){ cout << "\n释放子类对象\n"; } 32 }; 33 /*--------相当于在原有程序功能上增加了新的功能-----------*/ 34 son::son(string a, int i, int j):father(a,i)//不同之处 35 { 36 //name = a; 37 //tall = i; 38 cout << "\n在子类构造函数中\n"; 39 weight = j; 40 } 41 void son::print1() 42 { 43 father::print(); 44 cout << "体重:" <<weight; 45 } 46 int main() 47 { 48 son a("Mike", 180, 80); 49 a.print1(); 50 cout << "\n结束了\n"; 51 return 0; 52 }
结果显示
显然,方案二更好些。