码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 多重继承

时间:2019-11-16 23:19:16      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:new   pac   变量   turn   clu   RKE   列表   初始化列表   out   

#include <iostream>
/**
 * C++多重继承
 */

using namespace std;

class Farmer {
public:
    Farmer(string name = "jack");

    ~Farmer();

    void sow();

protected:
    string m_strName;
};

class Worker {
public:
    Worker(string code = "001");

    virtual ~Worker();

    void carry();

protected:
    string m_strCode;
};

void Worker::carry() {
    cout << m_strCode << endl;
    cout << "Worker::carry()" << endl;
}

class MigrantWorker : public Farmer, public Worker {
public:
    MigrantWorker(string name, string age);

    ~MigrantWorker();
};
Farmer::Farmer(string name) {
    m_strName=name;
    cout << "Farmer()" << endl;
}
Farmer::~Farmer() {
    cout << "~Farmer()" << endl;
}
void Farmer::sow() {
    cout << m_strName << endl;
    cout << "Farmer::sow()" << endl;
}
Worker::~Worker() {
    cout << "~Worker()" << endl;
}

Worker::Worker(string code) {
    m_strCode = code;
    cout << "Worker()" << endl;
}
//初始化列表的方式来初始化 name的值 和code 的值
//类似:student::student( string name): m_name(name)  将有值的数据 传递给()内的变量
MigrantWorker::MigrantWorker(string name, string code) : Farmer(name), Worker(code) {
    cout << "MigrantWorker()" << endl;
}

MigrantWorker::~MigrantWorker() {
    cout << "~MigrantWorker()" << endl;
}

int main() {
    MigrantWorker * migrantWorker=new MigrantWorker("kitty","002");
    migrantWorker->carry();
    migrantWorker->sow();
    delete(migrantWorker);
    return 0;
}

C++ 多重继承

标签:new   pac   变量   turn   clu   RKE   列表   初始化列表   out   

原文地址:https://www.cnblogs.com/wuyanzu/p/11874284.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!