首页 > 编程 > C++ > 正文

C++学习一虚继承

2019-11-11 06:07:42
字体:
来源:转载
供稿:网友

当需要使用菱形继承时,会出现这种情况:最顶端的基类被继承了两次,于是在内存中将有两个,而且分别存在。这样一般不符合我们的要求,所以会使用到虚继承。也就是在第一派生类中加入virtual虚继承顶端的基类。

以下代码就能很好的证明只要去掉virtual 就会显示两次调用Person的构造函数。这里如果使用虚继承,那么Person会只使用默认值,因为不可能继承两个的值,所以,只使用自己的默认值

#include <iostream>#include <stdlib.h>#include <string>using namespace std;class Person {public:	Person(string color = "blue"):m_strColor(color) {		cout << "Person()" << endl;	}	void PRintColor(void) {		cout << m_strColor << endl;	}	~Person() {		cout << "~Person()" << endl;	}private:	string m_strColor;};class Farmer :virtual public Person {public:	Farmer(string color):Person("Farmer" + color) {		cout << "Farmer()" << endl;	}	~Farmer() {		cout << "~Farmer()" << endl;	}};class Worker :virtual public Person {public:	Worker(string color):Person("Worker" + color) {		cout << "Worker()" << endl;	}	~Worker() {		cout << "~Worker()" << endl;	}};class MigrantWorker :public Worker, public Farmer {public:	MigrantWorker(string color):Worker(color),Farmer(color) {		cout << "MigrantWorker()" << endl;	}	~MigrantWorker() {		cout << "~MigrantWorker()" << endl;	}};int main(void) {	MigrantWorker *p = new MigrantWorker("yellow");	p->Worker::Person::PrintColor();	p->Farmer::Person::PrintColor();	delete p;	p = NULL;	system("pause");	return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选