2444: C++习题 对象转换
时间限制: 1 Sec 内存限制: 128 MB提交: 914 解决: 581
题目描述
定义一个Teacher(教师)类(教师号,姓名,性别,薪金)和一个Student(学生)类(学号,姓名,性别,成绩),二者有一部分数据成员是相同的,num(号码),name(姓名),sex(性别)。编写程序,将一个Student对象(学生)转换为Teacher(教师)类,只将以上3个相同的数据成员移植过去。可以设想为: 一位学生大学毕业了,留校担任教师,他原有的部分数据对现在的教师身份来说仍然是有用的,应当保留并成为其教师数据的一部分。
输入
一个教师的信息和一个学生的信息
输出
学生的信息和学生转换为教师后的信息
样例输入
10001 Li f 1234.5
20010 Wang m 89.5
样例输出
student1:
num:20010
name:Wang
sex:m
score:89.50
teacher2:
num:20010
name:Wang
sex:m
pay:1500.00
提示
主函数已给定如下,提交时不需要包含,会自动添加到程序尾部
int main()
{
cout<<setiosflags(ios::fixed);
cout<<setprecision(2);
int num;
char name[20];
char sex;
float score;
float pay;
cin>>num>>name>>sex>>pay;
Teacher teacher1(num,name,sex,pay);
cin>>num>>name>>sex>>score;
Student student1(num,name,sex,score);
cout<<"student1:"<<endl;
student1.display();
Teacher teacher2=Teacher(student1);
teacher2.setpay(1500);
cout<<"teacher2:"<<endl;
teacher2.display();
return 0;
}
迷失在幽谷中的鸟儿,独自飞翔在这偌大的天地间,却不知自己该飞往何方……
#include <iostream> #include <iomanip> using namespace std; class Student { public: Student(int n,char *na,char s,float sc):num(n),sex(s),score(sc) { int i; for(i=0; na[i]!=' '; i++) { name[i]=na[i]; } name[i]=' '; } void display() { cout<<"num:"<<num<<endl<<"name:"; for(int i=0; name[i]!=' '; i++)cout<<name[i]; cout<<endl<<"sex:"<<sex<<endl; cout<<"score:"<<score<<endl; } int num; char name[20],sex; float score,pay; }; class Teacher:public Student { public: Teacher(int n,char *na,char s,float p):Student(n,na,s,p),num(n),sex(s) {} Teacher(Student&a):Student(num,name,sex,score) { sex=a.sex; num=a.num; int i; for(i=0; a.name[i]!=' '; i++)name[i]=a.name[i]; name[i]=' '; } void setpay(int n) { pay=n; } void display() { cout<<"num:"<<num<<endl<<"name:"; for(int i=0; name[i]!=' '; i++)cout<<name[i]; cout<<endl<<"sex:"<<sex<<endl; cout<<"pay:"<<pay<<endl; } int num; char name[20],sex; float score,pay; }; int main() { cout<<setiosflags(ios::fixed); cout<<setprecision(2); int num; char name[20]; char sex; float score; float pay; cin>>num>>name>>sex>>pay; Teacher teacher1(num,name,sex,pay); cin>>num>>name>>sex>>score; Student student1(num,name,sex,score); cout<<"student1:"<<endl; student1.display(); Teacher teacher2=Teacher(student1); teacher2.setpay(1500); cout<<"teacher2:"<<endl; teacher2.display(); return 0; }