引:之前用过的Student类(学号,姓名,年龄)和Employee类(工号,姓名,部门),这两个类中有共同的地方,就是都包括姓名,甚至工号、学号也可以看成共同的地方。如果把Student、Employee类写得更详细些,比如学号(工号)姓名、性别、年龄、民族等等,有很多共同的地方。这样看来分别定义Student、Employee类就做了很多重复的工作,是否可以定义一个Person类,包括学号(工号)姓名、性别、年龄、民族等,将其稍加修改就可以生成Student、Employee类呢?可以!!
1.
从一个或多个以前定义的类(基类)产生新类的过程称为派生,这个新类又称为派生类。
例:
class Student: public Person//公有派生类、子类 Student
{};//子类虽然没有定义自己的成员,但它默认公有继承了父类的id和name。
void main()
{Student s1;
s1.id=”20105467”;
s1.name="王明";
cout<<s1.id<<’\t’<<s1.name<<endl;
}
2.下面是个具体例子:
#include <iostream>
#include <string>
using namespace std;
class Person
{
string id; string name;char gender;int age; //私有数据成员
public:
void input