虚继承是解决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;
}