B拥有类A的全部特点,则可以把A作为一个基类,B就是A的一个派生类

  • 派生类用用基类的全部成员函数和成员变量,不论是private、protected、public

    • 派生类的各个成员函数中,不能访问基类中的private成员
      1. class CStudent {
      2. private:
      3. string sName;
      4. int nAge;
      5. public:
      6. bool isThreeGood() {};
      7. void setName(const string & name)
      8. {sName = name;}
      9. // ...
      10. };
      11. class CundergraduateStudent:public CStudent {
      12. private:
      13. int nDepartment;
      14. public:
      15. bool isThreeGood() { ... } // 覆盖
      16. bool CanBaoYan() {...}
      17. };

      派生类对象的内存空间

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

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

image.png

实例:学籍管理

  1. class CStudent {
  2. private:
  3. string name;
  4. string id;
  5. char gender; // "F" & "M"
  6. int age;
  7. public:
  8. void PrintInfo();
  9. void SetInfo(const string & name_, const string & id_, int age_, char gender_);
  10. string GetName() {return name;}
  11. };
  12. class CUndergraduateStudent:public CStudent {
  13. private:
  14. string department;
  15. public:
  16. void QualifiedForBaoyan() {
  17. cout << "qualified for baoyan" << endl;
  18. }
  19. void PrintInfo() { // 因参数表和返回值类型相同,所以不是重载,是覆盖
  20. CStudent::PrintInfo(); // 调用基类的方法 不使用CStudent::的话,就成了递归
  21. cout << "Department:" << department << endl;
  22. }
  23. void SetInfo(const string & name_, const string & id_, int age_, char gender_,
  24. const string & department_) {
  25. CStudent::SetInfo(name_, id_, age_, gender_); // 调用基类的方法
  26. department = department_;
  27. }
  28. };