第4章继承机制
基类和派生类
单继承
派生类的访问控制
多继承
继承机制下的构造函数与析构函数
应用实例
继承的概念
1、继承的概念
以存在的类为基础定义新的类,新类即拥有基类的数据成员和成员函数。
Person
char * name;
char * id_card_no;
bool gender;
Student
char student_no;
Date enroll_date;
……
teacher
Date hire_date;
Degree degree;
……
Administrator
Date hire_date;
Rank rank;
……
继承的概念
通过继承机制,可以利用已有的数据类型来定义新的数据类型。
根据一个类创建一个新类的过程称为继承,也称派生。新类自动具有原有类的成员,根据需要还可以增加新成员。
派生新类的类称为基类,又称父类,而将派生出来的新类称为派生类,又称子类。
单继承-继承方式
继承语法形式
class B {……};
class D : [private | protected | public] B
{
……
};
基类子对象
派生类新定义成员
继承部分
派生部分
派生类对象
〈继承方式〉有三种:
public 表示公有继承方式 private 表示私有继承方式protected 表示保护继承方式
缺省情况下为私有继承方式。
派生类的访问控制
返回首页
公有继承
私有继承
保护继承
public
最常见的派生方式
基类的公有成员和保护成员被继承为派生类的公有成员和保护成员。
派生类不可直接访问基类的private成员,可通过基类的共有成员函数访问
基类子对象
派生类新定义成员
继承部分
派生部分
派生类对象
例题
class base{
Private: int x;
public:
void setx(int n) { x=n;}
int getx() { return x; }
void showx( )
{ cout<<x<<endl; }
};
class derived:public base{
Private: int y;
public:
void sety(int n) { y=n;}
void sety() { y=getx( ); }
void showy()
{ cout<<y<<endl; }
};
Setx()
Getx()
Showx()
x
Setx()
Getx()
Showx()
x
Sety()
Gety()
Showy()
y
接口
私有数据
base
derived
私有继承
私有继承时,在派生类中,基类的公有成员和保护成员作为派生类的私有成员,派生类的成员函数可以直接访问它们.
而派生类的成员函数无法直接访问基类的私有成员。
在类外部,派生类的对象无法访问基类的所有成员。
私有继承
【例】私有继承的例子
#include <iostream>
using namespace std;
class Base{
Private: int x;
public:
void setx(int n){x=n; }
int getx( ) {return x; }
void showx(){cout<<x<<endl; }
};
class derived:private base{
int y;
public:
void sety( int n){ y=n; }
void sety( ){ y=getx( ); }
void showy()
{ cout<<y<<endl; }
};
void main(){
derived obj;
(10); //cannot access
(20);
(); //cannot access
();
}
Setx()
Getx()
Showx()
x
Setx()
Getx()
Showx()
x
Sety()
Gety()
Showy()
y
接口
私有数据
base
Derived::
复习三 继承机制(new改) 来自淘豆网m.daumloan.com转载请标明出处.