1. Preface
Well, this series of blogs has become an embarrassing Reading Note for C++ Primer Plus.When using C language, code reuse is often achieved by adding library functions, but one drawback is that the original written code is not fully applicable to the current situation.Class inheritance in OOP design is more flexible than it is. It can add new data members and methods, modify the implementation details of inherited methods, and keep the original code.Get to the point.
Class Inheritance Example
The scenario is as follows: Now you need to record information about the members of table tennis, including their names and whether there are free tables.Some of the members have participated in the competition and their points in the competition need to be presented and recorded separately.Therefore, the class to which a member has participated in a competition is a derived class object that already belongs to the member's class.
Class declaration:
tabtenn.h1 #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 Is a base class 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);//Default constructor 31 RatedPlayer(unsigned int r,const TableTennisPlayer& tp);//Create Derived Class Object Constructor from Base Class Object 32 unsigned int Rating() const {return rating;} 33 void ResetRating (unsigned int r) {rating = r;} 34 }; 35 36 #endif