小甲鱼-虚继承

虚继承是解决C++多重继承问题的一种手段,从不同途径继承来的同一基类,会在子类中存在多份拷贝。这将存在两个问题:其一,浪费存储空间;第二,存在二义性问题,通常可以将派生类对象的地址赋值给基类对象,实现的具体方式是,将基类指针指向继承类(继承类有基类的拷贝)中的基类对象的地址,但是多重继承可能存在一个基类的多份拷贝,这就出现了二义性。
虚继承主要解决多继承中出现变量访问不明确的问题;
在这里插入图片描述
在一般的多重继承中,D继承来自B,C。而B,C都继承自C,因此在D中出现了2次A,

为了节省空间,可以将B,C对A的继承设定为虚拟继承,A就变成了虚拟基类
解决方法:

1.用类名+::来解决;

2.虚继承;

#include<iostream>
#include<string>
using namespace std;

class Person
{
public:
	Person(string theName);
	
	void introduce();
protected:
	string name;
};

class Teacher:virtual public Person
{
public:
	Teacher(string theName,string theClass);
	void teach();
	void introduce();
protected:
	string classes;
};
class Student:virtual public Person
{
public:
	Student(string theName,string theClass);
	void attendClass();
	void introduce();
protected:
	string classes;
};

class TeachingStudent:public Student,public Teacher
{
public:
	TeachingStudent(string theName,string classTeaching,string classAttending);
	void introduce();
};
Person::Person(string theName)
{
	name=theName;
}
void Person::introduce()
{
	cout<<"大家好,我是"<<name<<". \n\n";
}

Teacher::Teacher(string theName,string theClass):Person(theName)
{
	classes=theClass;
}

void Teacher::teach()
{
	cout<<name<<"教"<<classes<<endl;
}

void Teacher::introduce()
{
	cout<<"大家好,我是"<<name<<",我教"<<classes<<endl;
}

Student::Student(string theName,string theClass):Person(theName)
{
	classes=theClass;
}

void Student::attendClass()
{
	cout<<name<<"加入"<<classes<<"学习"<<endl;
}

void Student::introduce()
{
	cout<<"大家好,我是"<<name<<",我在"<<classes<<"学习"<<endl;
}

TeachingStudent::TeachingStudent(string theName,string classTeaching,string classAttending):Teacher(theName,classTeaching),Student(theName,classAttending),Person(theName)
{
}

void TeachingStudent::introduce()
{
	cout<<"大家好,我是"<<Student::name<<",我教"<<Teacher::classes<<endl;
	cout<<"同时我在"<<Student::classes<<"学习"<<endl;
}

int main()
{
	Teacher teacher("周帅~","C++入门班");
	Student student("段莉~","C++进阶班");

	TeachingStudent teachingStudent("周锻~","C++入门班","C++进阶班");
	teacher.introduce();
	teacher.teach();
	student.introduce();
	student.attendClass();
	teachingStudent.introduce();
	teachingStudent.teach();
	teachingStudent.attendClass();

	return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值