c++笔记之虚基类&菱形继承

版权声明:虽然写的很菜,但我也是有版权的! https://blog.csdn.net/weixin_42093825/article/details/82782611

简单例子:

#include <iostream>
#include <string>

using namespace std;

class Person
{
public:
	Person(string nam, char s, int a)
	{
		name = nam;
		sex = s;
		age = a;
	}
protected:
	string name;
	int age;
	char sex;
};


class Teacher :virtual public Person
{
public:
	Teacher(string nam, char s, int a, string t) :Person(nam, s, a)
	{
		title = t;
	}
protected:
	string title;
};

class Student :virtual public Person
{
public:
	Student(string nam,char s,int a,float sco):Person(nam,s,a),score(sco){}
protected:
	float score;
};
 
class Graduate :public Teacher, public Student
{
	public:
		Graduate(string nam,char s,int a,string t,float sco,float w)
			:Person(nam,s,a),Teacher(nam,s,a,t),Student(nam,s,a,sco),wage(w){}
		void show()
		{
			//这里之所以不存在二义性是因为这个菱形继承是虚基类继承,
			//虚基类继承时c++只执行最后的派生类Grauate对虚基类的构造函数的调用,
			//忽略虚基类的其他派生类的构造函数的调用,
                        //这保证了公共基类的数据成员不会被多次初始化。
			cout << "name: " << name << endl;  
			cout << "age: " << age << endl;
			cout << "sex; " << sex << endl;
			cout << "score: " << score << endl;
			cout << "title: " << title << endl;
			cout << "wages: " << wage << endl;
		}
private:
	float wage;
};
// practice.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
#include "pch.h"
#include "Person.h"
#include <iostream>

using namespace std;

int main()
{
	Graduate grad("Wang_li", 'f', 24, "assistant", 89.5, 1200);
	grad.show();
	system("pause");
	return 0;
}

     这是一个菱形继承,Teacher和Student都继承于Person类,并且Person都是作为两者的虚基类,Graduate继承于Student和Teacher类,这时虚基类的优点就发挥出来了,Graduate负责对虚基类Person的初始化,忽略Student和Teacher对Person构造函数的调用,避免多次初始化。Graduate只保留了基类的成员,所以不会产生二义性并且解决菱形继承带来的数据冗余。如果只是普通继承,需要指明name这些成员的类域,不然编译器就不知道是哪个类的成员。

                                                 

感谢我的朋友--小樊。

现在我的排名是1233662。

猜你喜欢

转载自blog.csdn.net/weixin_42093825/article/details/82782611