#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> #include<string.h> using namespace std; class student { private: long num; char* name; string major; char Class[4]; public: student(const char* nam); void show_stu(); }; student::student(const char* nam) { name = new char[strlen(nam) + 1]; strcpy(name, nam); cout << "分别输入学号和姓名: " << endl; cin >> num; cin >> name; cout << "输入专业:" << endl; cin >> major; cout << "输入班级:" << endl; cin >> Class[4]; } void student::show_stu() { cout << "学生信息: " << num << " " << name << endl; cout << " " << major << " " << Class[4] << endl; } class leader:public student { private: string position; public: leader(); }; leader::leader() { cout << "输入职位:" << endl; cin >> positon; } int main() { student a("fakeeeeee"); leader b("fakeeeeee"); a.show_stu(); b.show_stu(); return 0; }帮我修改上面代码
时间: 2024-01-21 08:02:14 浏览: 118
duojikongzhi.rar_Unsigned_c++include <reg51>
以下是修改后的代码:
```C++
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
class student {
private:
long num;
char* name;
string major;
char Class[5];
public:
student(const char* nam, long n, string mj, const char* cls);
void show_stu();
~student();
};
student::student(const char* nam, long n, string mj, const char* cls) {
name = new char[strlen(nam) + 1];
strcpy(name, nam);
num = n;
major = mj;
strcpy(Class, cls);
}
void student::show_stu() {
cout << "学生信息: " << num << " " << name << endl;
cout << " " << major << " " << Class << endl;
}
student::~student() {
delete[] name;
}
class leader :public student {
private:
string position;
public:
leader(const char* nam, long n, string mj, const char* cls, string pos);
void show_leader();
};
leader::leader(const char* nam, long n, string mj, const char* cls, string pos) :student(nam, n, mj, cls) {
position = pos;
}
void leader::show_leader() {
show_stu();
cout << " " << position << endl;
}
int main() {
const char* name = "fakeeeeee";
long num = 12345;
string major = "Computer Science";
const char* Class = "A101";
string position = "Monitor";
student a(name, num, major, Class);
leader b(name, num, major, Class, position);
a.show_stu();
b.show_leader();
return 0;
}
```
主要的修改如下:
1. 在 `student` 中增加了析构函数,避免内存泄漏。
2. 在 `student` 中的构造函数中,修正了 `Class` 数组越界的问题。
3. 在 `leader` 中的构造函数中,调用了 `student` 的构造函数,避免了重复输入学生信息的问题。
4. 在 `leader` 中增加了 `show_leader()` 函数,用于显示学生和领导的信息。
阅读全文