C++学习——类继承

来源:互联网 发布:券商资管新规 知乎 编辑:程序博客网 时间:2024/06/05 16:11

类继承(class inheritance)能够从已有的类派生出新的类,而派生类继承了原有类(称为基类)的特征,包括方法。通过继承完成的工作

1、在已有类的基础上添加功能

2、给类添加数据

3、修改类方法的行为

例如从TableTennisPlayer派生出RatedPlayer类

// tabtenn1.h -- a table-tennis base class#ifndef TABTENN1_H_#define TABTENN1_H_#include <string>using std::string;// simple base classclass TableTennisPlayer{private:    string firstname;    string lastname;    bool hasTable;public:    TableTennisPlayer (const string & fn = "none",                       const string & ln = "none", bool ht = false);    void Name() const;    bool HasTable() const { return hasTable; };    void ResetTable(bool v) { hasTable = v; };};// simple derived classclass RatedPlayer : public TableTennisPlayer{private:    unsigned int rating;public:    RatedPlayer (unsigned int r = 0, const string & fn = "none",                 const string & ln = "none", bool ht = false);    RatedPlayer(unsigned int r, const TableTennisPlayer & tp);    unsigned int Rating() const { return rating; }    void ResetRating (unsigned int r) {rating = r;}};#endif


0 0
原创粉丝点击