定一个学生类 Student,要求:Student 类具有私有成員属性,包括学号,姓名和性別。为Student 类编写不带参数的构造函数和带参数的构造函数,用于成员信号的初始化,为 Student 类编写析构函数,Student 类具有公有成员方法,可以品示输入学生信号和输出学生信息,编写main0 函数来使用该类,Student 类定义在文件Student.h文件中,Student 类成员函数定文在文件 Student.cpp 文件中 主西数定义在文件main.opp中。
时间: 2024-02-12 22:03:30 浏览: 26
好的,这是一个关于学生类的问题。我会根据你的要求进行回答。
首先,我们需要在一个名为Student.h的文件中定义Student类,包括私有成员属性和公有成员方法。代码如下:
```c++
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
class Student {
private:
string id;
string name;
string gender;
public:
Student(); // 不带参数的构造函数
Student(string id, string name, string gender); // 带参数的构造函数
~Student(); // 析构函数
void input(); // 输入学生信息
void output(); // 输出学生信息
};
#endif
```
接下来,在Student.cpp文件中,我们需要实现构造函数、析构函数和公有成员方法。代码如下:
```c++
#include "Student.h"
#include <iostream>
using namespace std;
Student::Student() {
this->id = "";
this->name = "";
this->gender = "";
}
Student::Student(string id, string name, string gender) {
this->id = id;
this->name = name;
this->gender = gender;
}
Student::~Student() {
cout << "学生" << this->name << "已被析构" << endl;
}
void Student::input() {
cout << "请输入学生信息:" << endl;
cout << "学号:";
cin >> this->id;
cout << "姓名:";
cin >> this->name;
cout << "性别:";
cin >> this->gender;
}
void Student::output() {
cout << "学生信息:" << endl;
cout << "学号:" << this->id << endl;
cout << "姓名:" << this->name << endl;
cout << "性别:" << this->gender << endl;
}
```
最后,在main.cpp文件中,我们可以使用Student类,创建学生对象并调用其公有成员方法。代码如下:
```c++
#include "Student.h"
int main() {
Student stu1; // 不带参数的构造函数
stu1.input();
stu1.output();
Student stu2("001", "张三", "男"); // 带参数的构造函数
stu2.output();
return 0;
}
```
这样,我们就完成了一个简单的学生类的定义和使用。