#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(const char* na) :student(na); }; leader::leader(const char* na) { cout << "输入职位:" << endl; cin >> positon; } int main() { student a("fakeeeeee"); a.show_stu(); leader b("fakeeeeee"); return 0; }帮我找出上面c++代码的bug
时间: 2024-01-21 09:02:14 浏览: 83
这段代码有一些错误:
1. 在 `student` 类中,`cin >> name` 会将已经通过 `new` 分配的内存丢失,应该改为 `cin >> name + 1`。
2. 在 `student` 类中,`cin >> Class[4]` 会导致越界访问,应该改为 `cin >> Class`。
3. 在 `leader` 类中,构造函数的声明应该为 `leader(const char* na) :student(na) {}`,而不是 `leader(const char* na) :student(na);`。
4. 在 `leader` 类中,`cin >> positon` 应该改为 `cin >> position`。
修改后的代码如下:
```
#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 + 1;
cout << "输入专业:" << endl;
cin >> major;
cout << "输入班级:" << endl;
cin >> Class;
}
void student::show_stu() {
cout << "学生信息: " << num << " " << name << endl;
cout << " " << major << " " << Class << endl;
}
class leader : public student {
private:
string position;
public:
leader(const char* na) : student(na) {};
};
int main() {
student a("fakeeeeee");
a.show_stu();
leader b("fakeeeeee");
return 0;
}
```
阅读全文