美文网首页
C++入门07 --多继承,菱形继承,虚继承,虚基类

C++入门07 --多继承,菱形继承,虚继承,虚基类

作者: YanZi_33 | 来源:发表于2021-08-13 11:05 被阅读0次

多继承

  • C++允许一个类有多个父类,不建议使用,会增加程序设计的复杂度;
#include <iostream>

using namespace::std;

class Student {
public:
    int m_score;
    
    Student(int score = 0) : m_score(score){ }

    ~Student(){
        cout << "~Student()" << endl;
    }
    
    void study(){
        cout << "Student study() -- score = " << m_score << endl;
    }
};

class Worker {
public:
    int m_salary;
    
    Worker(int salary = 0) : m_salary(salary){ }

    ~Worker(){
        cout << "~Worker()" << endl;
    }
    
    void work(){
        cout << "Worker work() -- salary = " << m_salary << endl;
    }
};

class Undergraduate : public Student,public Worker{
public:
    int m_grade;
    //初始化列表 调用父类的构造函数初始化父类的成员
    Undergraduate(int score = 0,int salary = 0,int grade = 0) : Student(score),Worker(salary),m_grade(grade){ }
    
    ~Undergraduate(){
        cout << "~Undergraduate()" << endl;
    }

    void play(){
        cout << "Undergraduate play() -- grade = " << m_grade << endl;
    }
};

int main(int argc, const char * argv[]) {

    Undergraduate ug;
    ug.m_score = 100;
    ug.m_salary = 2000;
    ug.m_grade = 4;
    ug.study();
    ug.work();
    ug.play();
    
    cout << sizeof(Undergraduate) << endl;
    
    return 0;
}
  • Undergraduate类继承自Student类与Worker类;

相关文章

网友评论

      本文标题:C++入门07 --多继承,菱形继承,虚继承,虚基类

      本文链接:https://www.haomeiwen.com/subject/hqtdbltx.html