最后的图是我想要输出的结果
#include<string>
using namespace std;
//多重继承
//二义性产生
//解决二义性问题
//虚基类 继承间接的基类person,
//把teacher与student公共的属性放到person中
//class person就是虚基类
//虚基类定义
class Person
{
public:
Person(string nam, int a, string s)
:name(nam), age(a), sex(s)
{
cout << "Person..." << endl;
}
~Person() { cout << "~~~Person..." << endl; }
//受保护的数据成员,便于子类直接访问
protected:
string name; int age; string sex;
};
class Teacher :virtual public Person
{
public:
Teacher(string nam_t, int a, string se, string t)
:Person(nam_t, a, se), title(t) {}
void display()
{
cout << "\n输出一个教师信息..\n";
cout << "name:" << name << " "
<< "age:" << age << " "
<< "sex:" << sex << " "
<< "职称:" << title << endl;
}
protected:
string title;//教师职称
};
//第二个基类学生
class Student :virtual public Person
{
public:
Student(string nam_s, int a, string se, float sco)
:Person(nam_s, a, se), score(sco) {}
void display()
{
cout << "\n输出一个学生信息..\n";
cout << "name:" << name << " "
<< "age:" << age << " "
<< "sex:" << sex << " "
<< "成绩:" << score << endl;
}
protected:
float score;
};
//子类研究生多重继承
class Graduate : public Teacher, public Student
{
public:
Graduate(string nam, int a, string s, string t, float sco, float w)
:Person(nam, a, s), Teacher(nam, a, s, t), Student(nam, a, s, sco), wage(w) {}
void display()
{
cout << "\n输出一个研究生信息..\n";
cout << "name\t" << " age " << " Sex "<< " Title " << " Score " << " Wage " << endl;
cout << name << "\t";
cout << age << " ";
cout << sex << " ";
cout << title << " ";
cout << score << " ";
cout << wage << endl;
}
protected:
float wage;
};
void main()
{
Teacher t1("孔子", 48, "F", "Prof");
Student s1("子张-学生", 20, "M", 98);
Graduate g1("颜回-高足", 18, "F", "Assi", 85.2, 8900);
Person*p;
p = &t1; p->display();
p = &s1;p->display();
p = &g1;p->display();
}