类继承(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 class
class 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 class
class 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
公有派生:基类的公有成员将成为派生类的公有成员,基类的私有部分也成为派生类的一部分,但只能通过基类的公有和保护访问方法访问
由于派生类不能直接访问基类成员,所以在创建派生类对象时,必须先创建基类对象,派生类的构造函数必须使用基类的构造函数
有关派生类构造函数要点:
1、基类对象首先被创建
2、派生类构造函数应该通过初始化成员列表将基类信息传递给基类构造函数
3、派生类构造函数应初始化派生类新增的数据成员
在释放对象的时候,先析构派生类对象,再析构基类对象
基类指针可以在不进行显示类型转换的情况下指向派生类对象,基类引用可以在不进行显示类型转换的情况下指向派生类引用,不过只能调用基类的方法
不可以把基类对象和地址赋给派生类
公有继承建立一种is-a(是一种)关系,派生类也是一种基类(香蕉是水果)
多态:同一个方法在不同的对象(例如基类对象和派生类对象)中的行为是不同的
两种方法实现多态公有继承:1、在派生类中重新定义基类的方法;2、使用虚方法
成员函数是虚拟的(virtual),程序将根据引用或指针指向的对象的类型来选择方法,基类的析构函数声明为虚拟的,确保释放派生对象时,按正确的顺序的调用析构函数
访问控制:protected
protected和private类似,在类外只能用公有类成员来访问protected部分中的类成员。区别在基类派生出的类体现:派生类的成员可以直接访问基类的保护成员,但不能访问基类的私有成员。