对象转换

Problem G: C++习题 对象转换

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 208   Solved: 110
[ Submit][ Status][ Web Board]

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;

}

#include <iostream>
#include<iomanip>
#include <cstring>

using namespace std;

class Teacher;

class Student
{
public:

    Student(){};

    Student (int &,char [20],char &,float &);

    friend class Teacher;

    void display()
    {
        cout<<"num:"<<num<<endl;
        cout<<"name:"<<name<<endl;
        cout<<"sex:"<<sex<<endl;
        cout<<"score:"<<score<<endl;
    }
private:

    int num;
    char name[20];
    char sex;
    float score;
};

Student::Student(int &i,char j[],char &k,float &l)
{
    num = i;
    strcpy(name,j);
    sex = k;
    score = l;
}
class Teacher
{

public:

    Teacher(){};

    void display();

    void setpay(int p);

    Teacher (int &,char [20],char &,float &);

    Teacher(Student&);

private:

    int num;
    char name[20];
    char sex;
    float pay;

};

Teacher::Teacher(int &i,char j[],char &k,float &l)
{
    num = i;
    strcpy(name,j);
    sex = k;
    pay = l;
}
void Teacher::setpay(int p)
{
    pay = p;
}

void Teacher::display()
{
    cout<<"num:"<<num<<endl;
    cout<<"name:"<<name<<endl;
    cout<<"sex:"<<sex<<endl;
    cout<<"pay:"<<pay<<endl;
}
Teacher::Teacher(Student &s)
{
    num = s.num;

    strcpy(name,s.name);

    sex = s.sex;

}


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;

}


你可能感兴趣的:(运算符重载,对象转换)