[Classes and Objects] Inservice (eden) 虚继承

c++多重继承 和 初始化列表

[Classes and Objects] Inservice (eden)

  • 题目描述
  • 答题区域
  • 提交记录
  • 成绩报告
  • 排名情况
  • 相关讨论
出题
邮箱
蔡桐钊
1262074036@qq.com
评测
截止时间
实时评测
2018-06-05 10:00
空间限制
时间限制
32MB
1000ms

Please complete the following 4 classes: Person, Student, Worker, Inservice.

Note:

  1. 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;
    
  2. 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"

  3. 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"

  4. 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);

还有一个问题是:最后编译通过了,但是输出是下面这样的
Construct Person
Construct Worker
Co nstruct Student
Construct InService
c++多重继承 和 初始化列表

这个注意在

class InService :public Student ,public Worker 这里的继承顺序就可以了,

继承顺序就是最后的构造函数调用的先后顺序;

多个基类的构造函数的调用次序:按基类在被继承时所声明的次序,从左到右依次调用

与它们在派生类构造函数实现中的初始化列表中出现的次序无关。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值