6、定义一个教师类和一个学生类,二者有一部分数据成员是相同的,例如 num,name,sex。请编程,将一个学生类对象转换为教师类,只将以上 3 个相同的数据成员移植过去。可以设想为:一位学生大学毕业了,留校担任教师,他原有的部分数据对现在的教师身份来说仍然是有用的,应当保留并成为其教师的数据的一部分。
时间: 2024-02-17 19:04:12 浏览: 190
好的,下面是一个实现将学生类对象转换为教师类对象的代码示例:
```c++
#include<iostream>
#include<string>
using namespace std;
class Person{
public:
Person(int n=0, string na="", char s=' '):num(n),name(na),sex(s){}
void display(){
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
}
protected:
int num;
string name;
char sex;
};
class Teacher: public Person{
public:
Teacher(int n=0, string na="", char s=' ', string t=""):Person(n, na, s),title(t){}
void display(){
Person::display();
cout<<"title:"<<title<<endl;
}
private:
string title;
};
class Student: public Person{
public:
Student(int n=0, string na="", char s=' ', int g=0):Person(n, na, s),grade(g){}
operator Teacher(){
Teacher t(num, name, sex, " ");
return t;
}
private:
int grade;
};
int main(){
Student s(1001, "Tom", 'M', 2);
cout<<"---Before conversion: Student---"<<endl;
s.display();
cout<<"---After conversion: Teacher---"<<endl;
Teacher t = s;
t.display();
return 0;
}
```
在上面的代码中,我们定义了一个 Person 类作为学生类和教师类的基类,其中包括了三个共同的数据成员:num、name、sex。我们还定义了一个 Teacher 类和一个 Student 类,分别继承自 Person 类,并在此基础上添加了额外的数据成员和成员函数。
在 Student 类中,我们重载了类型转换运算符,将 Student 类对象转换为 Teacher 类对象,并只保留了 Student 类中与 Person 类共同的数据成员。在 main 函数中,我们创建了一个 Student 类对象 s,并将其转换为 Teacher 类对象 t,最后分别输出了两个对象的信息。
需要注意的是,这种类型转换有一定的局限性,只能将 Student 类对象转换为 Teacher 类对象,并且只能转换 Student 类中与 Person 类共同的数据成员,其它的数据成员无法保存。
阅读全文
相关推荐


















