一、前言

  好吧,本系列博客已经变成了《C++ Primer Plus》的读书笔记,尴尬。在使用C语言时,多通过添加库函数的方式实现代码重用,但有一个弊端就是原来写好的代码并不完全适用于现在的情况。OOP设计思想中类的继承相比来说更为灵活,可以添加新的数据成员和方法,也能修改继承下来方法的实现细节,同时还保留了原有的代码。开始进入正题。

二、类继承示例

  场景如下:现需要记录乒乓球运动成员的信息,包括姓名和有无空余桌台。其中有一部分成员参加过比赛,需要将这一部分单独提出并记录他们在比赛中的比分。因此,参加过比赛的成员所属的类就是素有成员所属类的派生类对象了。

类声明:

 1 #ifndef TABTENN_H_
 2 #define TABTENN_H_
 3 
 4 #include <string>
 5 
 6 using std::string;
 7 
 8 class TableTennisPlayer
 9 {
10 private:
11     string firstname;
12     string lastname;
13     bool hasTable;
14 
15 public:
16     TableTennisPlayer (const string& fn = "none",
17                        const string& ln = "none",bool ht = false);
18     void Name() const;
19     bool HasTable() const {return hasTable;};
20     void ResetTable(bool v) {hasTable = v;};
21 };
22 
23 //derived class
24 class RatedPlayer:public TableTennisPlayer //TableTennisPlayer是基类
25 {
26 private:
27     unsigned int rating;
28 public:
29     RatedPlayer(unsigned int r = 0,const string& fn = "none",const string& ln = "none",
30                 bool ht = false);//默认构造函数
31     RatedPlayer(unsigned int r,const TableTennisPlayer&  tp);//通过基类对象创建派生类对象构造函数
32     unsigned int Rating() const {return rating;}
33     void ResetRating (unsigned int r) {rating = r;}
34 };
35 
36 #endif
tabtenn.h

相关文章:

  • 2021-06-11
  • 2021-08-09
  • 2022-12-23
  • 2021-12-05
  • 2021-12-07
  • 2021-06-01
  • 2021-10-25
  • 2022-12-23
猜你喜欢
  • 2021-11-22
  • 2022-02-28
  • 2021-07-08
  • 2021-08-27
  • 2022-12-23
  • 2021-09-13
  • 2021-05-31
相关资源
相似解决方案