题目要求
定义一个Teacher和Student类,二者有num,name,sex三个数据成员的相同的。编写程序将一个Student对象转换为Teacher类,只将这3个相同的数据成员移植过去。
用代码块功能插入代码,请勿粘贴截图
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<string>
using namespace std;
class Student{
public:
Student(int n, const char* nam, const char* s, int a) {
num = n;
strcpy(name, nam);
strcpy(sex, s);
age=a;
}
int get_num() {
return num;
}
char* get_name() {
return name;
}
char* get_sex() {
return sex;
}
void display() {
cout << "Student's info:" << endl << "Num:" << num << endl << "Name:" << name << endl << "Sex:" << sex << endl << "Age:" << age << endl;
}
private:
int num;
char* name;
char* sex;
int age;
};
class Teacher {
public:
Teacher(){}
Teacher(Student&);
Teacher(int n,const char* nam,const char* s, int sa) {
num = n;
strcpy(name, nam);
strcpy(sex, s);
salary = sa;
}
void display();
private:
int num;
char* name;
char* sex;
int salary = 1000;
};
Teacher::Teacher(Student& s) {
num = s.get_num();
strcpy(name, s.get_name());
strcpy(sex, s.get_sex());
}
void Teacher::display() {
cout << "Teacher's info:" << endl << "Num:" << num << endl << "Name:" << name << endl << "Sex:" << sex << endl << "Salary:" << salary << endl;
}
int main() {
Student s(123456, "Zhang", "female", 18);
s.display();
cout << endl;
Teacher t = Teacher(s);
t.display();
return 0;
}
运行结果及报错内容
我的解答思路和尝试过的方法
name和sex的类型改为char*,运行结果为空
我想要达到的结果
正确显示name和sex