博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
继承的作用以及在子类中初始化所有数据的方法
阅读量:4569 次
发布时间:2019-06-08

本文共 1981 字,大约阅读时间需要 6 分钟。

1.方便扩充程序,使之不必重写整个程序

代码示例

1 #include 
2 #include
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 father25 {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 << "体重:" <

 

运行结果

方案二

代码示例

1 #include 
2 #include
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 father25 {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 << "体重:" <

结果显示

显然,方案二更好些。

转载于:https://www.cnblogs.com/table/p/4721308.html

你可能感兴趣的文章
Vue2.x + vux2.x + vux-loader + typescript 搭建第一个环境
查看>>
MySQL的binlog日志
查看>>
vagrant The specified host network collides with a non-hostonly network!
查看>>
0x59 单调队列优化DP
查看>>
mysql中的union用法
查看>>
利用python爬取龙虎榜数据及后续分析
查看>>
Git和GitHub使用总结
查看>>
php array_multisort对数据库结果多个字段进行排序
查看>>
关于大型网站技术演进的思考(十六)--网站静态化处理—前后端分离—下(8)...
查看>>
Python中dict详解
查看>>
[LeetCode][JavaScript]House Robber
查看>>
java经典算法四十题
查看>>
(转载) MTK flash
查看>>
Python 序列化之json、pickle
查看>>
python3 多线程笔记
查看>>
无尽的控件-GridView复合表头
查看>>
Luogu4726 【模板】多项式指数函数(NTT+多项式求逆)
查看>>
e3mall商城的归纳总结2之认识dubbo、zookeeper
查看>>
纯js实现图片上传
查看>>
嵌入式SQL
查看>>