定义一个Teacher(教师)类和一个 Student( 学生)类,者有一部分数据成员 是相同的,例如num(号码), name(姓名),sex(性别)。编写程序,将一个Student对象(学生)转换为Teacher(教师)类,只将以上3个相同的数据成员移植过去。可以设想为:一位学生大学毕业了,留校担任教师,他原有的部分数据对现在的教师身份来说仍然是有用的,应当保留并成为其教师数据
#include<iostream>
#include<string.h>
using namespace std;
class Student{
public:
Student(int,string,char,float);
int getNum(){return num;}
string getName(){return name;}
char getSex(){return sex;}
float getScore(){return score;}
void display();
private:
int num;
string name;
char sex;
float score;
};
Student::Student(int num,string name,char sex,float score){
this->num=num;
this->name=name;
this->sex=sex;
this->score=score;
}
void Student::display(){
cout<<"num:"<<num<<"\nname:"<<name<<"\nsex:"<<sex<<"\nscore:"<<score<<endl;
}
class Teacher{
public:
Teacher(){}
Teacher(Student &);
Teacher(int,string,char,float);
void display();
private:
int num;
string name;
char sex;
float pay;
};
void Teacher::display(){
cout<<"num:"<<num<<"\nname:"<<name<<"\nsex:"<<sex<<"\nscore:"<<pay<<endl;
}
Teacher::Teacher(int num,string name,char sex,float pay){
this->num=num;
this->name=name;
this->sex=sex;
this->pay=pay;
}
Teacher::Teacher(Student &student){
this->num=student.getNum();
this->name=student.getName();
this->sex=student.getSex();
this->pay=1500;
}
int main(){
Student student1(1111,"Wang",'m',99);
Teacher teacher1(1001,"Li",'f',1234.5),teacher2;
cout<<"teacher1=\n";
teacher1.display();
cout<<endl;
cout<<"student1=\n";
student1.display();
cout<<endl;
teacher2=Teacher(student1);
cout<<"teacher2=\n";
teacher2.display();
return 0;
}
一部分。