C++ 虚继承

假如想象 提交于 2019-12-04 16:27:08

如果不虚继承的话,父类对象每一次被调用都会被初始化

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

using namespace std;
class Person {
public:
    Person(string color="blue");
    virtual ~Person();
    void printColor();
protected:
    string m_strColor;
};
//虚继承
class Farmer :virtual public Person{
public:
    Farmer(string name = "jack",string color="blue");

    ~Farmer();

    void sow();

protected:
    string m_strName;
};
//虚继承
class Worker :virtual public Person{
public:
    Worker(string code = "001",string color="bule");

    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,string color);

    ~MigrantWorker();
};


Person::Person(string color) {
    m_strColor=color;
    cout << "Person()" << endl;
}
void Person::printColor() {
    cout << m_strColor << endl;
    cout << "Person::printColor()" << endl;
}
Person::~Person() {
    cout << "~Person()" << endl;
}

Farmer::Farmer(string name,string color):Person(color) {
    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,string color):Person(color){
    m_strCode = code;
    cout << "Worker()" << endl;
}

MigrantWorker::MigrantWorker(string name, string code,string color) : Farmer(name,color), Worker(code,color) {
    cout << "MigrantWorker()" << endl;
}

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

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

不加virtual关键词 输出结果

Person 被初始化了两次
Person()
Farmer()
Person()
Worker()
MigrantWorker()
002
Worker::carry()
kitty
Farmer::sow()
~MigrantWorker()
~Worker()
~Person()
~Farmer()
~Person()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!