c++多重继承 和 初始化列表
[Classes and Objects] Inservice (eden)
Please complete the following 4 classes: Person, Student, Worker, Inservice.
Note:
Person owns data member name and sex, the output format is (For more detail, see the sample output):
// you should add this ouput statement in the constructor cout << "Construct Person" << endl; // you should add this ouput statement in the destructor cout << "Destruct Person" << endl;
Student is a derived class of Person, its data member is a string sno(学号), its constructor has to print "Construct Student" and its destructor has to print "Destruct Student"
Worker is a derived class of Person, its data member is a string wno(职员号), its constructor has to print "Construct Worker" and its destructor has to print "Destruct Worker"
Please think the relationship between InService and Student/Worker, and implement InService class by yourself. with its constructor prints "Construct InService" and its destructor prints "Destruct InService"
Sample Input
amblpo
1
13154671
10814061
Sample Output
Construct Person
Construct Student
Construct Worker
Construct InService
amblpo
1
amblpo
1
13154671
amblpo
1
10814061
Destruct InService
Destruct Worker
Destruct Student
Destruct Person
Hints
虚继承
分析问题:
这道题一般都会有一个错误:Person::Person(string s1, int x) 这个构造函数没有被调用;
下面是正确的继承方式:
Person::Person() ;
class Worker : virtual public Person ;
//定义为虚函数,因为它和student共同继承了,最后 InService又继承了一次,属于“多重继承”,这个时候就涉及到共享继承了
class Student : virtual public Person ;
class InService :public Student ,public Worker {
//这里不需要再继承一次person,因为它的父类已经继承过了
public:
InService();
~InService();
InService(string, int, string, string);
};
InService::InService() {
cout << "Construct InService" << endl;
}
InService::~InService() {
cout << "Destruct InService" << endl;
}
//问题来了:
InService::InService(string s1, int x, string s2, string s3):Person(s1,x),
Worker(s1,x,s3),
Student(s1,x,s2){
//这里的Person(s1,x)还要定义一次(如果没有就会是开始的那个现象:压根没有调用:Person(string s1, int x))
//不理解的朋友可以看看这篇代码: c++多重继承 和 初始化列表
cout << "Construct InService" << endl;
}// InService is(name, sex, sno, wno);
这个注意在
class InService :public Student ,public Worker 这里的继承顺序就可以了,
继承顺序就是最后的构造函数调用的先后顺序;
多个基类的构造函数的调用次序:按基类在被继承时所声明的次序,从左到右依次调用
与它们在派生类构造函数实现中的初始化列表中出现的次序无关。