1、编写一个学生和教师数据输入和显示程序,学生的数据有编号、姓名、班号和成绩,教师数据有编号、姓名、职称和部门。要求将编号、姓名输入和显示设计成一个类person,并作为学生数据操作类student和教师类teacher的基类。2、修改上一题程序,要求使用带参数的构造函数赋初值;
1 题目要求设计一个类person,存储学生或教师的编号和姓名,并将其作为学生类和教师类的基类。下面是一个可能的实现:
#include <iostream>
#include <string>
using namespace std;
class person
{
protected:
int id;
string name;
public:
void input()
{
cout << "请输入编号:";
cin >> id;
cout << "请输入姓名:";
cin >> name;
}
void output()
{
cout << "编号:" << id << endl;
cout << "姓名:" << name << endl;
}
};
class student : public person
{
int class_number;
double grade;
public:
void input()
{
person::input();
cout << "请输入班号:";
cin >> class_number;
cout << "请输入成绩:";
cin >> grade;
}
void output()
{
person::output();
cout << "班号:" << class_number << endl;
cout << "成绩:" << grade << endl;
}
};
class teacher : public person
{
string title;
string department;
public:
void input()
{
person::input();
cout << "请输入职称:";
cin >> title;
cout << "请输入部门:";
cin >> department;
}
void output()
{
person::output();
cout << "职称:" << title << endl;
cout << "部门:" << department << endl;
}
};
int main()
{
student s;
cout << "请输入学生信息:" << endl;
s.input();
cout << endl << "学生信息如下:" << endl;
s.output();
teacher t;
cout << endl << "请输入教师信息:" << endl;
t.input();
cout << endl << "教师信息如下:" << endl;
t.output();
return 0;
}
在这个实现中,将person类设计为一个基类,它包含了学生和教师共有的编号和姓名数据,这样的好处是可以避免代码重复。学生类和教师类分别继承person类,加上各自的属性和方法,实现了对学生和教师数据的输入和输出操作。
2 题目要求使用带参数的构造函数赋初值。下面是对上一个实现的修改,使用带参数的构造函数来初始化person类的数据:
#include <iostream>
#include <string>
using namespace std;
class person
{
protected:
int id;
string name;
public:
person(int id, string name) : id(id), name(name) {}
void output()
{
cout << "编号:" << id << endl;
cout << "姓名:" << name << endl;
}
};
class student : public person
{
int class_number;
double grade;
public:
student(int id, string name, int class_number, double grade)
: person(id, name), class_number(class_number), grade(grade) {}
void output()
{
person::output();
cout << "班号:" << class_number << endl;
cout << "成绩:" << grade << endl;
}
};
class teacher : public person
{
string title;
string department;
public:
teacher(int id, string name, string title, string department)
: person(id, name), title(title), department(department) {}
void output()
{
person::output();
cout << "职称:" << title << endl;
cout << "部门:" << department << endl;
}
};
int main()
{
student s(1, "小明", 1, 90);
cout << "学生信息如下:" << endl;
s.output();
teacher t(2, "张老师", "教授", "计算机系");
cout << endl << "教师信息如下:" << endl;
t.output();
return 0;
}
在这个实现中,在person类中添加了一个带参数的构造函数,用于初始化编号和姓名数据。在学生类和教师类中,调用了person类的构造函数,将编号和姓名数据初始化,同时传递学生和教师各自的数据,实现了进行对象初始化时属性值的调用。
# define _CRT_SECURE_NO_WARNINGS