【问题描述】定义并实现一个学生类(Student),类中的数据成员有:学生姓名、学生学号、人数和班级号。至少有一个公有成员函数(PrintStuInfo)。PrintStuInfo负责将相关信息输出。在类中定义静态数据成员,记录当
时间: 2024-03-26 16:35:33 浏览: 35
前学生数量,同时定义静态成员函数GetStuNum,用于获取当前学生数量。实现如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
// 构造函数
Student(string name, int id, int classNum) {
m_name = name;
m_id = id;
m_classNum = classNum;
m_stuNum++;
}
// 公有成员函数,用于输出学生信息
void PrintStuInfo() {
cout << "姓名:" << m_name << endl
<< "学号:" << m_id << endl
<< "班级号:" << m_classNum << endl;
}
// 静态成员函数,用于获取当前学生数量
static int GetStuNum() {
return m_stuNum;
}
private:
string m_name; // 学生姓名
int m_id; // 学生学号
int m_classNum; // 班级号
static int m_stuNum; // 静态数据成员,记录当前学生数量
};
int Student::m_stuNum = 0; // 静态数据成员初始化
int main() {
Student stu1("张三", 1001, 1);
Student stu2("李四", 1002, 1);
Student stu3("王五", 1003, 2);
stu1.PrintStuInfo();
stu2.PrintStuInfo();
stu3.PrintStuInfo();
cout << "当前学生数量:" << Student::GetStuNum() << endl;
return 0;
}
```
运行结果:
```
姓名:张三
学号:1001
班级号:1
姓名:李四
学号:1002
班级号:1
姓名:王五
学号:1003
班级号:2
当前学生数量:3
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)