首页 > 代码库 > C++习题 对象转换(定义一个Teacher(教师)类(教师号,姓名,性别,薪金)和一个Student(学生)类(学号,姓名,性别,成绩)编写程序,将一个Student对象(学生)转换为Teacher(教师)类。
C++习题 对象转换(定义一个Teacher(教师)类(教师号,姓名,性别,薪金)和一个Student(学生)类(学号,姓名,性别,成绩)编写程序,将一个Student对象(学生)转换为Teacher(教师)类。
Description
定义一个Teacher(教师)类(教师号,姓名,性别,薪金)和一个Student(学生)类(学号,姓名,性别,成绩),二者有一部分数据成员是相同的,num(号码),name(姓名),sex(性别)。编写程序,将一个Student对象(学生)转换为Teacher(教师)类,只将以上3个相同的数据成员移植过去。可以设想为: 一位学生大学毕业了,留校担任教师,他原有的部分数据对现在的教师身份来说仍然是有用的,应当保留并成为其教师数据的一部分。
Input
一个教师的信息和一个学生的信息
Output
学生的信息和学生转换为教师后的信息
Sample Input
10001 Li f 1234.5 20010 Wang m 89.5
Sample Output
student1: num:20010 name:Wang sex:m score:89.50 teacher2: num:20010 name:Wang sex:m pay:1500.00
HINT
主函数已给定如下,提交时不需要包含,会自动添加到程序尾部
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;
}
1 #include<iostream> 2 #include<iomanip> 3 #include<cstring> 4 using namespace std; 5 class Teacher; 6 class Student 7 {public: 8 void display() 9 {cout<<"num:"<<num<<endl<<"name:"<<name<<endl<<"sex:"<<sex<<endl<<"score:"<<score<<endl;} 10 Student(){}; 11 Student(int m,char n[20],char x,float s) 12 {num=m;strcpy(name,n);sex=x;score=s;} 13 int num; 14 char name[20]; 15 char sex; 16 float score; 17 }; 18 19 class Teacher 20 { 21 public: 22 void setpay(float a) 23 {pay=a;} 24 void display() 25 {cout<<"num:"<<num<<endl<<"name:"<<name<<endl<<"sex:"<<sex<<endl<<"pay:"<<pay<<endl;} 26 Teacher(){}; 27 Teacher(int m,char n[20],char x,float p) 28 {num=m;strcpy(name,n);sex=x;pay=p;} 29 Teacher(Student & s) 30 { 31 num=s.num; 32 strcpy(name,s.name); 33 sex=s.sex; 34 } 35 private: 36 int num; 37 char name[20]; 38 char sex; 39 float pay; 40 }; 41 int main() 42 { 43 cout<<setiosflags(ios::fixed); 44 cout<<setprecision(2); 45 int num; 46 char name[20]; 47 char sex; 48 float score; 49 float pay; 50 cin>>num>>name>>sex>>pay; 51 Teacher teacher1(num,name,sex,pay); 52 cin>>num>>name>>sex>>score; 53 Student student1(num,name,sex,score); 54 cout<<"student1:"<<endl; 55 student1.display(); 56 Teacher teacher2=Teacher(student1); 57 teacher2.setpay(1500); 58 cout<<"teacher2:"<<endl; 59 teacher2.display(); 60 return 0; 61 }