5-2 派生类的构造函数
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
通过本题目的练习可以掌握派生类构造函数的定义和使用方法。
要求定义一个基类Person,它有3个protected的数据成员:姓名name(char *类型)、性别 sex(char类型)、年龄age(int类型);一个构造函数用于对数据成员初始化;有一个成员函数show()用于输出数据成员的信息。
创建Person类的公有派生类Employee,增加两个数据成员 基本工资 basicSalary(int类型) 请假天数leaveDays(int型);为它定义初始化成员信息的构造函数,和显示数据成员信息的成员函数show()。
Input
共5个数据,分别代表姓名、性别、年龄、基本工资、请假天数。
Output
如示例数据所示,共5行,分别代表姓名、年龄、性别、基本工资、请假天数
Example Input
zhangsan m 30 4000 2
Example Output
name:zhangsan age:30 sex:m basicSalary:4000 leavedays:2
Hint
Author
#include <iostream>
using namespace std;
class Person
{
protected:
string name;
char sex;
int age;
public:
Person(string n, char s, int a) //基类构造函数
{
name = n;
sex = s;
age = a;
}
void show1() //基类输出函数
{
cout << "name:" << name << endl;
cout << "age:" << age << endl;
cout << "sex:" << sex << endl;
}
};
class Employee : public Person
{
private:
int basicSalary;
int leaveDays;
public:
Employee(string n, char s, int a, int b, int l) : Person(n, s, a) //派生类构造函数
{
basicSalary = b;
leaveDays = l;
}
void show() //派生类输出
{
show1();
cout << "basicSalary:" << basicSalary << endl;
cout << "leavedays:" << leaveDays << endl; //这里有个坑,注意以后输出有样例,一定要赋值样例
}
};
int main()
{
string n;
char s;
int a, b, l;
cin >> n >> s >> a >> b >> l;
Employee e(n, s, a, b, l);
e.show();
return 0;
}