虚继承要求
我们在framer中和worker中都引入了Person.h
当MigrantWorker继承自他们两。会引入两个Person
我们在被公共继承的类中应该这样写:
#ifndef PERSON_H//假如没有定义
#define PERSON_H//定义
//代码
//
#endif //结束符
附录完整代码:
#ifndef PERSON_H//假如没有定义
#define PERSON_H//定义
#include <string>
using namespace std;
class Person
{
public:
Person(string color = "blue");
virtual ~Person();
void printColor();
protected:
string m_strColor;
};
#endif //结束符
//
//
#include <iostream>
#include "Person.h"
using namespace std;
Person::Person(string color)
{
m_strColor = color;
cout << "person()" << endl;
}
Person::~Person()
{
cout << "~Person()" << endl;
}
void Person::printColor()
{
cout << m_strColor << endl;
cout << "Person -- printColor" << endl;
}
//
//
#include <string>
using namespace std;
#include "Person.h"
class Worker:public Person
{
public:
Worker(string code ="001",string color ="red");//希望worker可以传入肤色给person
virtual ~Worker();
void carry();
protected:
string m_strCode;
};
//
//
#include "Worker.h"
#include <iostream>
using namespace std;
Worker::Worker(string code,string color):Person(color)
{
m_strCode = code;
cout << "worker()" << endl;
}
Worker::~Worker()
{
cout << "~worker" << endl;
}
void Worker::carry()
{
cout << m_strCode << endl;
cout << "worker -- carry()" << endl;
}
//
//
#include <string>
using namespace std;
#include "Person.h"
class Framer:public Person
{
public:
Framer(string name = "jack",string color = "blue");
virtual ~Framer();
void sow();
protected:
string m_strName;
};
//
//
#include "Farmer.h"
#include <iostream>
using namespace std;
Framer::Framer(string name,string color):Person(color)
{
m_strName = name;
cout << "Framer()" << endl;
}
Framer::~Framer()
{
cout << "~Framer()" << endl;
}
void Framer::sow()
{
cout << m_strName << endl;
cout << "sow()" << endl;
}
//
//
#include <string>
#include "Farmer.h"
#include "Worker.h"
using namespace std;
class MigrantWorker:public Worker, public Framer//此处顺序决定实例化顺序。
{
public:
MigrantWorker(string name,string code,string color);
~ MigrantWorker();
private:
};
//
//
#include "MigrantWorker.h"
#include <iostream>
using namespace std;
MigrantWorker::MigrantWorker(string name,string code,string color): Framer(name,color), Worker(code,color)
{
cout <<":MigrantWorker()" << endl;
}
MigrantWorker::~MigrantWorker()
{
cout << "~MigrantWorker()" << endl;
}
//
//
#include <iostream>
#include "MigrantWorker.h"
#include <stdlib.h>
int main()
{
system("pause");
return 0;
}
可以正常用过编译说明我们用宏定义成功的解决了菱形问题的重定义报错。
c++虚继承(编码二)
与上面代码相同。
int main()
{
MigrantWorker *p = new MigrantWorker("merry", "200", "yellow");
delete p;
p = NULL;
system("pause");
return 0;
}