一,多继承
#include<iostream>
#include<string>
using namespace std;
class B1
{
public:
B1(int i){cout<<"B1类"<<" "<<i<<endl;}
};//定义基类B1
class B2
{
public:
B2(int j) {cout<<"B2类"<<" "<<j<<endl;}
};//定义基类B2
class B3
{
public:
B3() {cout<<"B3类"<<endl;}
};//定义基类B3
class B4
{
public:
B4() {cout<<"B4类"<<endl;}
};
class C: public B2, public B1, public B4,public B3
{
public:
C(int a,int b,int c,int d,int e)
:B1(a),memberB2(d),memberB1(c),B2(b)
{m=e; cout<<"consC"<<endl;}
private:
B1 memberB1;
B4 memberB4;
B3 memberB3;
B2 memberB2;
int m;
};//继承类C
void main()
{
C c(1,2,3,4,5);
}//主函数
C类按照顺序继承B2,B1,B4,B3;再按照数据成员定义顺序:memberB1, memberB4, memberB3,memberB2;最后是自己的构造器
二,虚继承
#include<iostream>
#include<string>
using namespace std;
class Person
{
protected:
string name;
public:
Person(string thename){name=thename;}
void introduce(){cout<<"大家好,我是"<<name<<endl;}
};
class Teacher:virtual public Person//虚继承:以后Teacher继承出去的子类不会自动继承Person类
{
protected:
string classes;
public:
Teacher(string thename,string theclass);
void teach(){cout<<name<<"教"<<classes<<endl;}
void introduce(){cout<<"大家好,我是"<<name<<",我教"<<classes<<endl;}
};
class Student:virtual public Person
{
protected:
string classes;
public:
Student(string thename,string theclass);
void attendClass(){cout<<name<<"加入"<<classes<<"学习"<<endl;}
void introduce(){cout<<"大家好,我是"<<name<<",我在"<<classes<<"学习"<<endl;}
};
class TeachingStudent:public Teacher,public Student
{
public:
TeachingStudent(string thename,string classTeaching,string classAttending);
void introduce();
};
Teacher::Teacher(string thename,string theclass):Person(thename)//构造函数的继承(含参数)
{
classes=theclass;
}
Student::Student(string thename,string theclass):Person(thename)
{
classes=theclass;
}
TeachingStudent::TeachingStudent(string thename,
string classTeaching,
string classAttending)
:Teacher(thename,classTeaching),Student(thename,classAttending),Person(thename)//Teacher和Student虚继承于Person,所以他们的子类TeachingStudent不继承于Person
{
}
void TeachingStudent::introduce()
{
cout<<"大家好,我是"<<name<<"。我教"<<Teacher::classes<<endl;
cout<<"同时我在"<<Student::classes<<"学习"<<endl;
}
void main()
{
Teacher teacher("techerJack","C");
Student student("studentTom","C");
TeachingStudent teachingStudent("Lily","C","C++");
teacher.introduce();
teacher.teach();
student.introduce();
student.attendClass();
teachingStudent.introduce();
teachingStudent.teach();
teachingStudent.attendClass();
}
如果不是虚继承,则TeachingStudent类将拥有2个name,
void TeachingStudent::introduce()
{
cout<<"大家好,我是"<<Student::name<<"。我教"<<Teacher::classes<<endl;
cout<<"同时我在"<<Student::classes<<"学习"<<endl;
}