C++ 继承和派生 及 学生管理范例

1、概念

继承:在定义一个新的类B时,如果该类与某个已知类A相似(指的是B拥有A的全部特点),那么就可以把A作为一个基类,而把B作为一个派生类(也称子类)。

  • 派生类是通过对基类进行修改和扩充得到的。在派生类中,可以扩充新的成员变量和成员函数。
  • 派生类一经定义后,可以独立使用,不依赖于基类。
  • 派生类拥有基类的全部成员函数和成员变量,不论是private,protected 还是 public
  • 在派生类的各个成员函数中,不能访问基类中的private成员。

2、需要继承机制的例子 - 学生管理系统

所有的学生都有的共同属性:

  • 姓名
  • 学号
  • 性别
  • 成绩

所有的学生都有的共同方法(成员函数)

  • 是否该留级
  • 是否该奖励

而不同的学生,又有各自不同的属性和方法

  • 研究生:有导师和系
  • 大学生:有系
  • 中学生:有竞赛特长加分

3、派生类的写法

class 派生类名 : public 基类名 
{

};

 

4、派生类对象的内存空间

派生类对象的体积,等于基类对象的体积,再加上派生类对象自己的成员变量的体积。

在派生类对象中,包含着基类对象,而且基类对象的存储位置位于派生类对象新增的成员

变量之前。如下代码示:

#include <iostream>
#include <string.h>

using namespace std;

class CBase {
    int v1, v2;
};

class CDerived : public CBase {
    int v3;
};

int main()
{
    printf("sizeof(CDerived) = %d\n", sizeof(CDerived));

    return 0;
}

输出的结果是:12

 

5、继承实例程序:学籍管理

#include <iostream>
#include <string.h>

using namespace std;

class CStudent {

private:
    string name;
    string id; // student number
    char gender; // 'F' for female, 'M' for male
    int age;

public:
    void PrintInfo() {
        cout << "name: " << name << endl;
        cout << "id: " << id << endl;
        cout << "gender: " << gender << endl;
        cout << "age: " << age << endl;
    }
    void SetInfo(const string & name_, const string & id_,
                 int age_, char gender_) {
        name = name_;
        id = id_;
        age = age_;
        gender = gender_;
    }
    string GetName() { return name; }
};

class CUndergraduateStudnet : public CStudent
{
private:
    string department; // 学生所属的系

public:
    void QualifiedForBaoyan() {
        cout << "qualified for baoyan" << endl;
    }

    void PrintInfo() {
        CStudent::PrintInfo(); // 调用基类的PrintInfo
        cout << "Department:" << department << endl;
    }

    void SetInfo(const string &name_, const string &id_,
                 int age_, char gender_, const string & department_) {
        CStudent::SetInfo(name_, id_, age_, gender_); // 调用基类的SetInfo
        department = department_;
    }
};

int main()
{
    CUndergraduateStudnet s2;
    s2.SetInfo("Harry Potter", "115200", 20, 'M', "CS");
    cout<< s2.GetName() << endl;
    s2.QualifiedForBaoyan();
    s2.PrintInfo();

    return 0;
}

执行结果如下:

posted @ 2015-03-19 22:06  阿青1987  阅读(940)  评论(2编辑  收藏  举报