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

2021-08-13  本文已影响0人  YanZi_33

多继承

#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;
}
上一篇 下一篇

猜你喜欢

热点阅读