当在多条继承路径上有一个公共的基类,在这些路径中的某几条汇合处,这个公共的基类就会产生多个实例(或多个副本),若只想保存这个基类的一个实例,可以将这个公共基类说明为虚基类。
在继承中产生歧义的原因有可能是继承类继承了基类多次,从而产生了多个拷贝,即不止一次的通过多个路径继承类在内存中创建了基类成员的多份拷贝。虚基类的基本原则是在内存中只有基类成员的一份拷贝。这样,通过把基类继承声明为虚拟的,就只能继承基类的一份拷贝,从而消除歧义。用virtual限定符把基类继承说明为虚拟的。
#include<iostream>
#include<string.h>
using namespace std;
class Person
{
public:
Person(string nam, char s, int a)
{
name = nam;
sex = s;
age = a;
}
protected:
string name;
char sex;
int age;
};
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()
{
cout << "name:" << name << endl;
cout << "age:" << age << endl;
cout << "title:" << title << endl;
cout << "sex:" << sex << endl;
cout << "score:" << score << endl;
cout << "wage:" << score << endl;
}
private:
float wage;
};
int main(void)
{
Graduate grad1("Wang_li", 'f', 24, "assistant", 89.5, 2400);
grad1.show();
return 0;
}